如何让温斯顿每日文件旋转login到相应的级别文件

我已经为我的应用程序定义了自定义级别,如下所示。

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

我正在使用每日文件旋转运输来获得每日login在单独的文件。

  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',它将创build一个名为info.log的日志文件,并将logging级别'info','warn'和'error'(跟踪和debugging将被忽略)。

但是我想要的行为是不同的。 如果我指定的级别是'信息',我logging级别'信息','警告'和'错误',那么应该为每种types的日志创build单独的文件。 即'信息'级别应logging到info.log和'警告'级别logging到warn.log。

我已经尝试指定五个不同的日常文件旋转运输,每个具有独特的水平。 那么我发现的问题是有重复的日志条目。 例如,如果logging“错误”级别,则当日志logging级别设置为info时,它将logging到info.log,warn.log和error.log。

我怎样才能达到我的目标?

根据温斯顿的文档,默认行为是logging所有具有至less指定重要性的日志级别的消息。

Winston允许您在每个传输器上定义一个级别属性,它指定传输器应logging的最大消息级别。

但是有办法达到你的要求。
我会尽力向你展示一些可能性,你可以select最适合你的方法。


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

您可以创build自定义传输并仅logging所需的级别。
这里只是给你一个想法的例子:

 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

这是原始winston软件包的一个分支。 这个fork在https://github.com/damianof/winston
此版本添加了一个levelOnly选项,使winston日志只有指定的级别。


最后,我想鼓励你阅读这些有关的讨论: