如何让Winston每日文件rotate到相应级别的文件中

How to get Winston daily file rotate to log to corresponding level file

我已经为我的应用程序定义了自定义级别。它们如下。

protected levels: Level = {
        "error": 0,
        "warn": 1,
        "info": 2,
        "debug": 3,
        "trace": 4
    };

我正在使用每日文件轮换传输来获取单独文件中的每日日志。

    const options: Object = {
        name: this.level,
        filename: logFilePath,
        dirname: WinstonLogAgent.DIR_LOG,
        datePattern: "yyyyMMdd.",
        prepend: true,
        level: this.level,
        levels: this.levels,
        maxsize: this.maxFileSize,
        maxFiles: this.maxFileCount,
        handleExceptions: true,
        humanReadableUnhandledException: true
    };

    this.transportInstance.push(new (winston.transports.DailyRotateFile)(options));

如果我将日志级别定义为 'info',它将创建一个名为 info.log 的日志文件,并将记录级别 'info' 、 'warn' 和 'error'(跟踪和调试将被忽略)。

但我想要的行为是不同的。如果我将级别指定为 'info' 并且我的日志记录级别为 'info' 、 'warn' 和 'error' ,那么应该为每种类型的日志创建单独的文件。即 'info' 级别应记录到 info.log 和 'warn' 级别应记录到 warn.log.

我试过指定五个不同的日常文件轮换传输,每个都有独特的级别。然后我发现的问题是有重复的日志条目。 例如,如果正在记录 'error' 级别,当日志级别设置为 info.

时,它将记录到 info.log、warn.log 和 error.log

我怎样才能实现我的 objective?

根据 Winston 的文档,默认行为是记录所有至少具有指定重要性或日志记录级别的消息。

Winston allows you to define a level property on each transport which specifies the maximum level of messages that a transport should log.

但是有一些方法可以达到你的要求。
我会尝试向您展示一些可能性,您可以选择最适合您的方法。


1。自定义传输(推荐):

您可以创建自定义传输并仅记录您想要的级别。
这里有一个例子只是为了给你一个想法:

let mainLogger = new (winston.Logger)({
  transports: [
    new (winston.transports.Console)(),
  ]
});

class CustomTransport extends winston.Transport {
  constructor(options) {
    super(options);
    this.name = 'customLogger';
    this.level = options && options.level || 'info';
    this.levelOnly = options && options.levelOnly;
    this.levels = options && options.levels || [];
  }

  log(level, msg, meta, callback) {
    if (!this.levelOnly || this.levels.indexOf(level) > -1) {
      mainLogger[level](msg, meta);
    }
    callback(null, true);
  }
}

winston.transports.CustomTransport = CustomTransport;

let myLogger = new winston.Logger({
  transports: [
    new (winston.transports.CustomTransport)({
      levelOnly: true,
      levels: ['info'],
    }),
  ]
});

myLogger.info('will be logged');
myLogger.warn('will NOT be logged');
myLogger.info('will be logged as well');

2。使用 winston-levelonly

This is a fork of the original winston package. The fork is at https://github.com/damianof/winston
This version adds a levelOnly option to make winston log only the specified level.


最后,我想鼓励您阅读这些相关讨论: