【问题标题】:write the timestamp first in nodejs winston logger首先在nodejs winston logger中写入时间戳
【发布时间】:2019-10-19 02:33:09
【问题描述】:

我试图让时间戳首先出现,但它总是添加到 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"}

【问题讨论】:

    标签: node.js logging winston


    【解决方案1】:

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

    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

    【讨论】:

      【解决方案2】:

      您可以使用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});
      }));
      

      【讨论】:

        猜你喜欢
        • 2019-07-04
        • 2019-01-25
        • 2014-08-30
        • 1970-01-01
        • 2021-04-26
        • 2018-06-10
        • 2022-01-06
        • 1970-01-01
        • 2018-08-06
        相关资源
        最近更新 更多