Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

write the timestamp first in nodejs winston logger

I have tried to make the timestamp appear first but it is always added to the end of the json.

I have used this configuration:

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

and got a log like:

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

All I want is that it will look like:

{"timestamp":"2019-06-03 17:01:10.054","level":"info","message":"app is loaded"}
like image 276
Mithir Avatar asked Mar 03 '23 21:03

Mithir


1 Answers

You can develop own formatter

const winston = require('winston');

class TimestampFirst {
    constructor(enabled = true) {
        this.enabled = enabled;
    }
    transform(obj) {
        if (this.enabled) {
            return Object.assign({
                timestamp: obj.timestamp
            }, obj);
        }
        return obj;
    }
}

var myFormat = winston.format.combine(
    winston.format.timestamp({
        format: 'YYYY-MM-DD HH:mm:ss.SSS'
    }),
    new TimestampFirst(true),
    winston.format.json()
);

winstonLogger = winston.createLogger();
winstonLogger.configure({
    level: 'info',
    format: myFormat,
    transports: [
        new winston.transports.Console(),
    ]
});


winstonLogger.info('hello', {
    message: 'test'
});

More information https://github.com/winstonjs/logform

like image 183
Yaroslav Gaponov Avatar answered Mar 27 '23 03:03

Yaroslav Gaponov