Search code examples
javascriptnode.jsloggingnpmwinston

Winston outputs json instead of formatted string


I have set up a simple winston logger in my app like this:

function logger(success, msg) {
    let now = new Date().toUTCString()
    let logger = new (winston.Logger)({
        transports: [
            new (winston.transports.File)({ 
                filename: 'log.log',
                timestamp: function() {
                    return new Date().toUTCString();
                },
                formatter: function(options) {
                    return `>>>>>>>>>> ${options.timestamp()} - ${options.level.toUpperCase} - ${options.message}`;
                }
            })
        ]
    });

    if (success) {
        logger.log('info', msg)
    } else {
        logger.log('error', msg)
    }
}

But instead of logging the formatted string, it outputs the following:

{"level":"error","message":"Nothing to upload","timestamp":"Mon, 23 Apr 2018 13:53:01 GMT"}

Ideas? Am I missing something? (Of course I am)


Solution

  • As you can find out in winston documentation for File you can set property json to false if you don't want information in file to be JSON objects. By default this property is true.

    json: If true, messages will be logged as JSON (default true).

    Could you try to change your code like this:

    function logger(success, msg) {
        let now = new Date().toUTCString()
        let logger = new (winston.Logger)({
            transports: [
                new (winston.transports.File)({ 
                    filename: 'log.log',
                    timestamp: function() {
                        return new Date().toUTCString();
                    },
                    json: false,
                    formatter: function(options) {
                        return `>>>>>>>>>> ${options.timestamp()} - ${options.level.toUpperCase} - ${options.message}`;
                    }
                })
            ]
        });
    
        if (success) {
            logger.log('info', msg)
        } else {
            logger.log('error', msg)
        }
    }