Search code examples
node.jswinston

Winson with timestamp not adding timestamps


I created a simple Winston logger for my node application, but the configuration with timestamps not working, what it means? It means that all of the logs isn't with the timestamp.

Example:

const { createLogger, format, transports } = require('winston');
const logger = createLogger({
    transports: [
        new transports.File({
            maxsize: 5120000,
            maxFiles: 20,
            filename: `logs/logs.log`,
            colorize: true,
            json: true,
            timestamp: true
        }),
        new transports.Console({
            level: "debug",
            timestamp: true,
            format: format.combine(
                format.colorize(), 
                format.simple(),
                format.timestamp()
            )
        })
    ]
});


module.exports = { logger };

Solution

  • simple() format does not output timestamp. so you should define a custom format using printf:

    const { createLogger, format, transports } = require('winston');
    
    const myFormat = format.printf(({ level, message, label, timestamp }) => {
      return `${timestamp} [${label}] ${level}: ${message}`;
    });
    
    const logger = createLogger({
        transports: [
            new transports.File({
                maxsize: 5120000,
                maxFiles: 20,
                filename: `logs/logs.log`,
                timestamp: true,
                json: true,
            }),
            new transports.Console({
                level: "debug",
                timestamp: true,
                format: format.combine(
                    format.timestamp(),
                    format.colorize(), 
                    myFormat,
                )
            })
        ]
    });
    
    
    module.exports = { logger };
    

    i also moved timestamp() format before the myFormat as it should fill timestamp of message before it reaches the printf.