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

后端 未结 9 623
清歌不尽
清歌不尽 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: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"}
    

提交回复
热议问题