Winston: how to add timestamp to logged output?

Created on 6 Aug 2016  路  5Comments  路  Source: winstonjs/winston

Most helpful comment

In winston@3 this can be achieved using custom formatters (in fact there's an example in the docs now: https://github.com/winstonjs/winston/blob/master/examples/custom-timestamp.js). Related discussion in #1134 for example. Thanks!

All 5 comments

You can do it manually if you want fine-grained control over your output:

var moment = require('moment'),
      timestamp = moment().format('DD-MM-YYYY HH:mm:ss');

logger.error(timestamp + 'error string');

Or the easy (and probably more consistent way) is just to set timestamp: true in your transport:

new winston.transports.Console({
            level: 'debug',
            handleExceptions: true,
            json: false,
            colorize: true,
            timestamp: true
        })
    ]

I haven't tried it but winston-logentries the transport for logentries.com looks good.

I normally create a custom logger

module.exports = new (winston.Logger)({
  level: 'info',
  handleExceptions: false,
  transports: [
    new (winston.transports.Console)({
      timestamp() {
        return moment().format('YYYY-MM-DD HH:mm:ss.SSSS');
      },
      formatter(params) {
        // Options object will be passed to the format function.
        // It's general properties are: timestamp, level, message, meta.
        const meta = params.meta !== undefined ? util.inspect(params.meta, { depth: null }) : '';
        return `[${params.timestamp}] [${params.level}] [${pkg.name}] *** ${params.message} ${meta}`;
      },
    }),
  ],
});

Thanks @osukaa . I realized I need to require() 'moment' (3rd party module) and 'util' (Node.js) module.
But where does pkg come from? It is not defined. I guess it is your own stuff.
There is also a typo in the code because params.timestamp function is not called, should be: params.timestamp().
Here is the metadata is logged a bit more differently:
https://github.com/winstonjs/winston/blob/master/README.md#user-content-custom-log-format
Did not take the time to understand both, so don't know which one is better, or what the point is to log metadata.

const winston = require( 'winston' );
const tsFormat = () => ( new Date() ).toLocaleDateString() + ' - ' + ( new Date() ).toLocaleTimeString();
const logger = new (winston.Logger)({
    transports: [
        // colorize the output to the console
        new ( winston.transports.Console )({ 
            timestamp: tsFormat,
            colorize: true,
            level: env === 'development' ? 'verbose' : 'info',
        })
    ]
});

In winston@3 this can be achieved using custom formatters (in fact there's an example in the docs now: https://github.com/winstonjs/winston/blob/master/examples/custom-timestamp.js). Related discussion in #1134 for example. Thanks!

Was this page helpful?
0 / 5 - 0 ratings