关于node.js:使用自定义格式化程序在Winston中记录元数据

Logging metadata in Winston with custom formatter

我正在尝试使用Winston记录stacktrace以及错误消息。
我的记录器配置了自定义格式化程序:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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}';
                }),
            ),
        })
    ]
});

我记录了错误以及stacktrace:

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

在我的日志中,有一行:

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

如何在自定义格式化程序中访问随消息传递给error函数的元数据?


我一直在研究类似的问题。最后,我做到了:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
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');