Mithir
Mithir

Reputation: 2423

use a different property name for timestamp in nodejs winston logger

I am using winstonjs logger with the timestamp formatter.

I saw there is an option to supply an alias, and I understood that this is the way to change the timestamp property name, but it only adds another timestamp property with the alias name... so for example:

    var myFormat = winston.format.combine(winston.format.timestamp({format:'YYYY-MM-DD HH:mm:ss.SSS', alias:'Date'}),
                                          winston.format.json());
    this.winstonLogger = winston.createLogger();
    this.winstonLogger.configure({
        level: 'info',
        format: myFormat,
        transports: [
            new winston.transports.Console(),
          ]
    });

will result in logs like this:

{"level":"info","message":"app is loaded","timestamp":"2019-06-03 17:01:10.054","Date":"2019-06-03 17:01:10.054"}

So there are 2 timestamp properties, one named "timestamp" and one named "Date" as I requested.

Am I using this wrong? Is there another way to do this?

Upvotes: 0

Views: 1133

Answers (1)

v1shva
v1shva

Reputation: 1599

Strangely though when adding an alias will add it as a separate timestamp entry. I think as a workaround you can try this.

const winston = require('winston'); 
const {createLogger, format, transports, info} = require('winston');

const removeTimestamp = format((info, opts) => {
  if (info.timestamp) {
    delete info.timestamp;
    return info;
  }
});

this.winstonLogger = createLogger({
  // To see more detailed errors, change this to 'debug'
  level: 'info',
  format: format.combine(
      format.timestamp({
        format: 'YYYY-MM-DD HH:mm:ss.SSS',
        alias: 'Date',
      }),
      removeTimestamp(),
      format.json(),
  ),
  transports: [
    new transports.Console()
  ],
});

Upvotes: 2

Related Questions