Stephen Last
Stephen Last

Reputation: 5781

NodeJS - Winston file transport with pretty JSON

I'm using Winston for logging to a file. I would like to log to a file in a human readable way and have JSON objects formatted with line breaks and tabs.

I'm trying to use the formatter function.

var winston = require('winston');
var moment = require('moment');

function formatter(args) {
    var date = moment().format("D/MM/YYYY hh:mm:ss");
    var msg = date + ' - ' + args.level + ' - ' + args.message + ' - ' + JSON.stringify(args.meta);
    return msg;
}

var logger = new (winston.Logger)({
    transports: [
        new (winston.transports.File)({
            level: 'silly',
            filename: __dirname + '/logs/test.log',
            json: false,
            formatter: formatter
        })
    ]
});

logger.log('info', 'info 123', { some: 'json' });

Output:

16/12/2015 12:23:44 - info - info 123 - {"some":"json"}

If I don't use JSON.stringify I just get [object Object].

What I'd like to get to is:

16/12/2015 12:23:44 - info - info 123 - 
{
    "some":"json"
}

Can Winston do this out the box in some way..?

...or is there a function someone has written that find {} in a string and adds the line breaks and tabs..?

Upvotes: 3

Views: 1569

Answers (1)

robertklep
robertklep

Reputation: 203534

Like this?

var msg = date         + ' - '   + 
          args.level   + ' - '   + 
          args.message + ' - \n' + JSON.stringify(args.meta, null, 2);

Upvotes: 2

Related Questions