Nodejs Winston DailyRotateFile 自定义格式化程序

Nodejs Winston DailyRotateFile custom formatter

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

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

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 库本身的公共模块。 有什么想法吗?

将 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 : '')
   }
  })