【问题标题】:winston:how to change timestamp format温斯顿:如何更改时间戳格式
【发布时间】:2012-12-08 21:15:26
【问题描述】:

我正在使用 winston 在 node.js 中添加日志详细信息,我使用以下过程添加日志

 var winston = require('winston');         
 winston.remove(winston.transports.Console);
 winston.add(winston.transports.Console, {'timestamp':true,'colorize':true);
 winston.log('info','jjjj');

我得到的输出是

2012-12-21T09:32:05.428Z - info: jjjj

我需要为 mytimestamp 指定格式,winston 中是否有任何规定可以这样做,非常感谢您的帮助

【问题讨论】:

    标签: node.js winston


    【解决方案1】:

    timestamp 选项可以是一个函数,它返回您希望保存的内容...

    第 4 行:

    winston.add(winston.transports.Console, {'timestamp':function() {return '111111111'; },'colorize':true});
    

    来源:https://github.com/flatiron/winston/pull/120

    【讨论】:

    • 你知道你在 21/12/12 12:21 回答了这个问题吗?!这是一个关于日期格式的问题:)
    • @yuyue007 似乎适用于winston 0.9.0版本的文件传输。
    【解决方案2】:

    为了获得好的结果,您可以使用momentjs:

    const moment = require('moment');
    ...
    ...
    timestamp: () => moment().format('YYYY-MM-DD hh:mm:ss')
    

    【讨论】:

      【解决方案3】:

      winston@3 版本

      winston.createLogger({
        format: winston.format.combine(
          winston.format.timestamp({format: 'YYYY-MM-DD HH:mm:ss'}),
          winston.format.prettyPrint()
        ),
        transports: [
          new winston.transports.Console()
        ]
      })
      

      要支持时区,您需要将format 更改为winston 将调用的函数。

      const timezoned = () => {
        return new Date().toLocaleString('en-US', {
          timeZone: 'Asia/Shanghai'
        });
      };
      
      const logger = createLogger({
        format: combine(
          timestamp({
            format: timezonedTime
          })
        ),
        transport: [
          new transports.Console(),
        ]
      });
      

      【讨论】:

      • 如何更改时区。 Winston 默认以 UTC 格式显示时间戳?
      • 我已经更新了答案。这是我在学习winston时写的一篇旧文章。 medium.com/@ThreePotatoteers/…
      【解决方案4】:

      要更改winston日志格式的时间戳格式,我们可以将字符串或返回字符串的函数作为参数传递给winston.format.timestamp(format)函数带格式参数。另外,我们可以使用combine函数来自定义日志格式

       const LOG_FORMAT = WINSTON.format.combine(
          WINSTON.format.align(),
          WINSTON.format.timestamp({format:'DD-MM-YYYY T hh:mm:ss.sss A'}),
          
          WINSTON.format.printf(({ level, message, timestamp, label }) => {
              return `[ ${level.toUpperCase()} | ${timestamp} | LOG:${message} ]`;
          })
      )
          const APP_LOGGER = WINSTON.createLogger({
          format: LOG_FORMAT,
          transports: [
              new WINSTON.transports.Console(),
              new WINSTON.transports.File({
                  filename: './logs/app.log'
              })
          ]
      })
      

      【讨论】:

      • 感谢莫哈巴蒂的即兴表演
      猜你喜欢
      • 2020-11-05
      • 2021-02-23
      • 2018-11-19
      • 1970-01-01
      • 1970-01-01
      • 2018-07-01
      • 1970-01-01
      • 2016-08-29
      • 1970-01-01
      相关资源
      最近更新 更多