winston:如何更改时间戳格式

Ama*_*a G 27 node.js winston

我使用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');
Run Code Online (Sandbox Code Playgroud)

我得到的输出是

2012-12-21T09:32:05.428Z - info: jjjj
Run Code Online (Sandbox Code Playgroud)

我需要为mytimestamp指定一种格式,在winston有任何提供这样做的任何帮助都会非常感激

Ben*_*ans 46

时间戳选项可以是一个函数,它返回您希望将其保存为...

第4行:

winston.add(winston.transports.Console, {'timestamp':function() {return '111111111'; },'colorize':true});
Run Code Online (Sandbox Code Playgroud)

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

  • 你是否意识到你在12月21日12:21回答了这个问题?!这是一个关于日期格式化的问题不少:) (127认同)

Chr*_*eng 9

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()
  ]
})
Run Code Online (Sandbox Code Playgroud)

要支持时区,您需要更改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(),
  ]
});
Run Code Online (Sandbox Code Playgroud)


小智 5

要更改winston日志格式中的时间戳格式,我们可以传递一个字符串或一个返回字符串作为参数的函数给winston.format.timestamp(format)采用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'
        })
    ]
})
Run Code Online (Sandbox Code Playgroud)