winston:how to change timestamp format

2020-05-29 21:57发布

问题:

I am using winston to add log details in node.js, i used the following procedure to add the logs

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

the output that i got is

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

I need to specify a format for mytimestamp , is there any provision to do so in winston any help will be much appreciated

回答1:

The timestamp option can be a function that returns what you wish it to be saved as...

Line 4:

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

Source here: https://github.com/flatiron/winston/pull/120



回答2:

winston@3 version

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

To support timezone, you need to change format to a function which winston will call.

const timezoned = () => {
  return new Date().toLocaleString('en-US', {
    timeZone: 'Asia/Shanghai'
  });
};

const logger = createLogger({
  format: combine(
    timestamp({
      format: timezonedTime
    })
  ),
  transport: [
    new transports.Console(),
  ]
});


回答3:

for a good result, you may use momentjs:

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