创建您自己的Winston日志文件

Create your own Winston logger files

本文关键字:日志 文件 Winston 自己的 创建      更新时间:2023-09-26

下面是我设置的一个基本的winston记录器:

var winston = require('winston')
var systemLogger = new (winston.Logger)({
  transports: [
    new (winston.transports.File)({
      name: 'system-file',
      // log which stores all the errors
      filename: './test.log',
      json: true,
      timestamp: true
    })
  ]
})
systemLogger.log('info', 'hello')
systemLogger.log('error', '-----hello2')

这样创建一个日志文件:

{"level":"info","message":"hello","timestamp":"2016-08-18T11:48:22.081Z"}
{"level":"error","message":"-----hello2","timestamp":"2016-08-18T11:48:22.083Z"}

但是我想让它在文件中看起来像这样:

INFO: 2016-08-18T11:48:22.081Z hello 
ERROR: 2016-08-18T11:48:22.083Z *** -----hello2 *** 

这可能吗?

我读了这个- https://github.com/winstonjs/winston#custom-log-format但我实际上找不到如何做到这一点-如果可能的话。

我已尝试添加格式化程序:

  formatter: function(options) {
    // Return string will be passed to logger.
    if (options.level === 'error') {
      return options.timestamp() +' ******** '+ options.level.toUpperCase() +' ******** '+ (undefined !== options.message ? options.message : '') 
    }
    else if (options.level === 'info') {
      return options.timestamp() +' '+ options.level.toUpperCase() +' '+ (undefined !== options.message ? options.message : '') 
    }
  }

然而,这似乎只适用于控制台打印,而不适用于文件。

在您的日志设置代码中,您必须放置formatter和您从formatter返回的任何字符串,它将显示在日志文件中。

formatter: function(options) {
        // Return string will be passed to logger.
        return options.timestamp() +' '+ options.level.toUpperCase() +' '+ (undefined !== options.message ? options.message : '') +
          (options.meta && Object.keys(options.meta).length ? ''n't'+ JSON.stringify(options.meta) : '' );
      }

因此,上面的格式化程序将首先打印时间戳,然后是日志级别,然后是您记录的实际消息。

希望对您有所帮助....

您需要创建一个formatter函数:

$ cat logger.js 
var winston = require('winston');
module.exports = (function(){
    function formatter (args){
            var timestamp = new Date().toISOString(),
                level =  args.level.toUpperCase(),
                message = args.message;
        return level+": "+timestamp+" "+message ;
    }
    return new (winston.Logger)({
        transports: [
            new (winston.transports.Console)({
                formatter: formatter,
            }),
            new (winston.transports.File)({
                formatter: formatter,
                filename : "./logs/custom-logger.log",
                maxsize : 1024 * 1024 * 500,
                maxFiles : 10,
                json : false,
                tailable : true,
            })
        ]
    });
}()); 

你所需要做的就是添加这个:json : false

所以它看起来像这样:

var winston = require('winston')
var systemLogger = new (winston.Logger)({
  transports: [
    new (winston.transports.File)({
      name: 'system-file',
      json : false,
      // log which stores all the errors
      filename: './test.log',
      json: true,
      timestamp: true
    })
  ]
})

你很接近,做得好!