使用winston

时间:2018-01-25 06:16:20

标签: node.js logging winston

const tsFormat = () => (new Date()).toLocaleTimeString();
const logger = new (winston.Logger)({
  transports: [
    // colorize the output to the console
    new (winston.transports.Console)({
      timestamp: tsFormat,
      colorize: true,
      level: 'info'
    }),
    new (require('winston-daily-rotate-file'))({
      filename: `${app_config.logfolder}/-${app_config.application[APP_NAME].logfile}`,
      timestamp: tsFormat,
      datePattern: 'dd-MM-yyyy',
      prepend: true,
      handleExceptions: true,
      level:app_config.application[APP_NAME].loglevel
    })
  ]
});

我已将记录器配置为所需级别。但之后我必须使用logger.info或其他日志级别。那么我有没有办法像logger.log这样做而不指定日志级别,因为我已经配置了我的日志级别。

每次配置我的日志级别后使用日志级别都没有意义。

1 个答案:

答案 0 :(得分:0)

基本上将自定义日志记录方法封装在单独的模块中并重用它

// in MyLogger.js
const tsFormat = () => (new Date()).toLocaleTimeString();
const logger = new (winston.Logger)({
  transports: [
    // colorize the output to the console
    new (winston.transports.Console)({
      timestamp: tsFormat,
      colorize: true,
      level: 'info'
    }),
    new (require('winston-daily-rotate-file'))({
      filename: `${app_config.logfolder}/-${app_config.application[APP_NAME].logfile}`,
      timestamp: tsFormat,
      datePattern: 'dd-MM-yyyy',
      prepend: true,
      handleExceptions: true,
      level:app_config.application[APP_NAME].loglevel
    })
  ]
});

exports.log = function(message) {
     logger.log('info', message);
}

// in consumer.js
var log = require('MyLogger');
log('My log message');