【问题标题】:Nodejs Winston DailyRotateFile custom formatterNodejs Winston DailyRotateFile 自定义格式化程序
【发布时间】:2018-10-29 20:13:56
【问题描述】:

我使用 DailyRotateFile 有一段时间了,对结果很满意。但现在我正在尝试包含一些专门针对我们业务的关键字,例如环境、交易 ID 等。我只知道我们有“元”参数来提供一些额外的信息,但我真的想要一个自定义格式化程序,因为否则开发人员每次想要记录一些东西时都需要注意这个额外的参数。

这么说,我将此代码添加到我的记录器设置中。

const transports = [

  new (winston.transports.DailyRotateFile)({
    filename: './logs/scrapper.log',
    datePattern: 'yyyy-MM-dd.',
    prepend: true,
    colorize: true,
    level: config.get('logging.level'),
    zippedArchive: false,
    timestamp: function(){
    return Date.now();
    },
    formatter: function(options){
      return options.timestamp() + '-' + process.env.NODE_ENV + '- 
      message:' + (options.message ? options.message : '')
   }
  }),
  new (winston.transports.Console)({
    timestamp: function() {
      return Date.now();
    },
    formatter: function(options) {
      return options.timestamp() + '-' + process.env.NODE_ENV + '- 
     message: ' + (options.message ? options.message : '')
   }
  })
];

有趣的是,它与控制台传输完美配合,但 DailyRotateFile 的传输却不是这样。我仍然获得日志文件的默认格式。 深入研究库代码后,我发现options.formatter 参数并没有完全进入winston 库本身的通用模块。 有什么想法吗?

【问题讨论】:

    标签: node.js winston


    【解决方案1】:

    将 JSON 设置为 false 以在每日旋转文件中使用自定义格式化程序

    new (winston.transports.DailyRotateFile)({
        filename: './logs/scrapper.log',
        datePattern: 'yyyy-MM-dd.',
        prepend: true,
        colorize: true,
        json:false, //Setting JSON as false
        level: config.get('logging.level'),
        zippedArchive: false,
        timestamp: function(){
        return Date.now();
        },
        formatter: function(options){
          return options.timestamp() + '-' + process.env.NODE_ENV + '-message:' + (options.message ? options.message : '')
       }
      })
    

    【讨论】:

    • 很好,请按照回答结束此问题
    猜你喜欢
    • 2014-08-30
    • 2017-03-24
    • 2019-02-08
    • 2018-12-29
    • 1970-01-01
    • 1970-01-01
    • 2018-02-15
    • 2016-11-30
    • 2018-10-19
    相关资源
    最近更新 更多