How can I add timestamp to logs using Node.js library Winston?

后端 未结 9 626
清歌不尽
清歌不尽 2021-01-31 12:55

I want to add timestamp to logs. What is the best way to achieve this?

9条回答
  •  一整个雨季
    2021-01-31 13:50

    We can do like this also

    var winston = require('winston');
    const { createLogger, format, transports } = require('winston');
    var config = require('../configurations/envconfig.js');
    
    var loggerLevel = process.env.LOGGERLEVEL ||  config.get('LOGGERLEVEL');
    
    var logger = winston.createLogger({
      format: format.combine(
        format.timestamp({
          format: 'YYYY-MM-DD HH:mm:ss'
        }),
        format.printf(info => `${info.timestamp} ${info.level}: ${info.message}`+(info.splat!==undefined?`${info.splat}`:" "))
      ),
      transports: [
        new (winston.transports.Console)({ level: loggerLevel }),
      ]
    });
    module.exports = logger;
    

提交回复
热议问题