Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Logging metadata in Winston with custom formatter

I'm trying to log stacktrace along with error message using Winston. My logger is configured with custom formatter:

this.errorLogger = winston.createLogger({
    levels: this.levels,
    level: 'error',
    transports: [
        new WinstonFileRotator({
            filename: '%DATE%.log',
            dirname: 'logs/error',
            zippedArchive: true,
            maxSize: '20m',
            maxFiles: '14d',
            handleExceptions: true,
            json: false,
            format: winston.format.combine(
                winston.format.timestamp({
                    format: 'YYYY-MM-DD HH:mm:ss'
                }),
                winston.format.printf(info => {
                    return '[${info.timestamp}] -> ${info.message}';
                }),
            ),
        }) 
    ]
});

I log the error along with stacktrace:

this.errorLogger.error('My message', ex.Stack);

In my log I have a line:

[2018-09-03 23:41:14] -> My message

How can I access in my custom formatter the metadata that I passed to error function along with the message?

like image 909
jmazur Avatar asked Dec 17 '22 21:12

jmazur


1 Answers

I have been working on a similar issue. In the end, I did:

const winston = require('winston');

const logger = winston.createLogger({
    level: 'info',
    format: winston.format.combine(
        winston.format.label({ label: 'MY-SILLY-APP' }),
        winston.format.timestamp(),
        winston.format.metadata({ fillExcept: ['message', 'level', 'timestamp', 'label'] }),
        winston.format.colorize(),
        winston.format.printf(info => {
            let out = `${info.timestamp} [${info.label}] ${info.level}: ${info.message}`;
            if (info.metadata.error) {
                out = out + ' ' + info.metadata.error;
                if (info.metadata.error.stack) {
                    out = out + ' ' + info.metadata.error.stack;
                }
            }
            return out;
        }),
    ),
    transports: [
        new winston.transports.Console()
    ]
});

logger.info('running');
try {
    throw new Error('failed');
} catch (err) {
    logger.error('failing', { error: err });
}
logger.info('stopping');
like image 177
geisshirt Avatar answered Jan 07 '23 07:01

geisshirt