How to log JavaScript objects and arrays in winston as console.log does?

In Winston > 3 you can use

logger.log('%o', { lol: 123 }')

Anyway... Couldn't accept that I have to use %o always and made this simple solution:

const prettyJson = format.printf(info => {
  if (info.message.constructor === Object) {
    info.message = JSON.stringify(info.message, null, 4)
  }
  return `${info.level}: ${info.message}`
})

const logger = createLogger({
  level: 'info',
  format: format.combine(
    format.colorize(),
    format.prettyPrint(),
    format.splat(),
    format.simple(),
    prettyJson,
  ),
  transports: [
    new transports.Console({})
  ],
})

So this logger....

  logger.info({ hi: 123 })

...transforms to this in the console

info: {
    "hi": 123
}

logger.log("info", "Starting up with config %j", config);

Winstons uses the built-in utils.format library. https://nodejs.org/dist/latest/docs/api/util.html#util_util_format_format_args


Use the built-in Node.js function util.format to convert your objects to strings in the same way that console.log does.


try changing prettyPrint parameter to

prettyPrint: function ( object ){
    return JSON.stringify(object);
}