首先在nodejs winston logger中编写时间戳

时间:2019-06-03 14:05:00

标签: node.js logging winston

我试图使时间戳首先出现,但始终将其添加到json的末尾。

我使用了以下配置:

    var myFormat = winston.format.combine(winston.format.timestamp({format:'YYYY-MM-DD HH:mm:ss.SSS'}),
                                          winston.format.json());
    this.winstonLogger = winston.createLogger();
    this.winstonLogger.configure({
        level: 'info',
        format: myFormat,
        transports: [
            new winston.transports.Console(),
          ]
    });

并得到类似以下的日志:

{"level":"info","message":"app is loaded","timestamp":"2019-06-03 17:01:10.054"}

我只想要它看起来像:

{"timestamp":"2019-06-03 17:01:10.054","level":"info","message":"app is loaded"}

2 个答案:

答案 0 :(得分:0)

您可以开发自己的格式化程序

const winston = require('winston');

class TimestampFirst {
    constructor(enabled = true) {
        this.enabled = enabled;
    }
    transform(obj) {
        if (this.enabled) {
            return Object.assign({
                timestamp: obj.timestamp
            }, obj);
        }
        return obj;
    }
}

var myFormat = winston.format.combine(
    winston.format.timestamp({
        format: 'YYYY-MM-DD HH:mm:ss.SSS'
    }),
    new TimestampFirst(true),
    winston.format.json()
);

winstonLogger = winston.createLogger();
winstonLogger.configure({
    level: 'info',
    format: myFormat,
    transports: [
        new winston.transports.Console(),
    ]
});


winstonLogger.info('hello', {
    message: 'test'
});

更多信息https://github.com/winstonjs/logform

答案 1 :(得分:0)

您可以使用JSON.stringify()printf()。只需将您的myFormat变量更改为此:

var myFormat = winston.format.combine(
  winston.format.timestamp({format: 'YYYY-MM-DD HH:mm:ss.SSS'}),
  winston.format.printf((info) => {
    return JSON.stringify({timestamp: info.timestamp, 
                           level: info.level, 
                           message: info.message});
}));