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

后端 未结 9 622
清歌不尽
清歌不尽 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;
    
    0 讨论(0)
  • 2021-01-31 13:52

    Another solution is wrapping the logger into a file that exports some functions like logger.info(), logger.error(), etc. then you just pass an extra key to be sent on every message log.

    loggerService.js

    const logger = winston.createLogger({ ... })
    
    function handleLog(message, level) {
      const logData = {
        timestamp: Date.now(),
        message,
      }
    
      return logger[level](logData)
    }
    
    function info(message) {
      handleLog(message, 'info')
    }
    
    function error(message) {
      handleLog(message, 'error')
    }
    
    function warn(message) {
      handleLog(message, 'warn')
    }
    
    module.exports = {
      info,
      error,
      warn
    }
    

    whatever-file.js

    const logger = require('./services/loggerService')
    
    logger.info('Hello World!')
    

    your-log.log

    {"timestamp":"2019-08-21 06:42:27","message":"Hello World!","level":"info"}
    
    0 讨论(0)
  • 2021-01-31 13:53

    Above answers did not work for me. In case you are trying to add timestamp to your logs using the latest version of Winston - 3.0.0-rc1, this worked like charm:

        const {transports, createLogger, format} = require('winston');
    
        const logger = createLogger({
            format: format.combine(
                format.timestamp(),
                format.json()
            ),
            transports: [
                new transports.Console(),
                new transports.File({filename: 'logs/error/error.log', level: 'error'}),
                new transports.File({filename: 'logs/activity/activity.log', level:'info'})
            ]
        });
    

    I used 'format.combine()'. Since I needed timestamp on all my transports, I added the formatting option within the createLogger, rather than inside each transport. My output on console and on file (activity.log) are as follows:

    {"message":"Connected to mongodb","level":"info","timestamp":"2018-02-01T22:35:27.758Z"}
    {"message":"Connected to mongodb","level":"info","timestamp":"2018-02-01T22:35:27.758Z"}
    

    We can add formatting to this timestamp in 'format.combine()' as usual using:

    format.timestamp({format:'MM-YY-DD'})
    
    0 讨论(0)
提交回复
热议问题