34

When I create a nodejs winston console logger and set json:true, it always output JSON logs in multiline format. If I pipe these to a file and try to grep that file, my grep hits only include part of the log line. I want winston to output my log lines in JSON format, but not to pretty print the JSON

Here is my config (coffeescript, apologies):

winston = require 'winston'
logger = new (winston.Logger)(
  transports: [
    new winston.transports.Console({
     json: true
    })
  ]
)

And some sample output:

{
  "name": "User4",
  "level": "info",
  "message": "multi line whyyyyy"
}
zayquan
  • 7,544
  • 2
  • 30
  • 39

5 Answers5

54

winston 3.x (current version)

Default formatter

const winston = require('winston');
const logger = winston.createLogger({
  format: winston.format.json(),
  transports: [
    new winston.transports.Console()
  ]
});

Example

const test = { t: 'test', array: [1, 2, 3] };
logger.info('your message', test);
// logger output:
// {"t":"test","array":[1,2,3],"level":"info","message":"your message"}

Custom formatter

const winston = require('winston');

const { splat, combine, timestamp, printf } = winston.format;

// meta param is ensured by splat()
const myFormat = printf(({ timestamp, level, message, meta }) => {
  return `${timestamp};${level};${message};${meta? JSON.stringify(meta) : ''}`;
});

const logger = winston.createLogger({
  format: combine(
    timestamp(),
    splat(),
    myFormat
  ),
  transports: [
    new winston.transports.Console()
  ]
});

Example:

const test = { t: 'test', array: [1, 2, 3] };
// NOTE: wrapping object name in `{...}` ensures that JSON.stringify will never 
// return an empty string e.g. if `test = 0` you won't get any info if 
// you pass `test` instead of `{ test }` to the logger.info(...)
logger.info('your message', { test });
// logger output:
// 2018-09-18T20:21:10.899Z;info;your message;{"test": {"t":"test","array":[1,2,3]}}

winston 2.x (legacy version)

It seems that the accepted answer is outdated. Here is how to do this for current winston version (2.3.1):

var winston = require('winston');
var logger = new (winston.Logger)({
  transports: [
    new (winston.transports.Console)({
     json: true,
     stringify: (obj) => JSON.stringify(obj),
    })
  ]
})

Note the parenthesis around winston.transports.Console.

jmarceli
  • 19,102
  • 6
  • 69
  • 67
  • I've made this the accepted answer but have not had a chance to test. If anyone finds that this does not work with the versions indicated please let me know – zayquan Jul 26 '17 at 05:10
  • I get an error pointing to the open bracket after Console: `TypeError: (intermediate value) is not a function` with `"winston": "^3.0.0-rc1"` – krivar Apr 13 '18 at 09:44
  • 1
    This is deprecated in version ^3.0.0. – Harshal Yeole Jun 10 '18 at 08:32
  • I am using winston 2.x and it is working as expected – Shivaji Mutkule Jun 24 '21 at 09:06
  • For folks having issue with `meta`, showing up try splitting the meta parameter like so: `const myFormat = printf(({ timestamp, level, message, ...meta }) => { ... });` – Ka Mok Jul 11 '22 at 17:54
3

The winston transports provide a way to override the stringify method, so by modifying the config above I got single line JSON output.

New config:

winston = require('winston')
logger = new (winston.Logger)({
  transports: [
    new winston.transports.Console({
     json: true,
     stringify: (obj) => JSON.stringify(obj)
    })
  ]
})
Dana Woodman
  • 4,148
  • 1
  • 38
  • 35
zayquan
  • 7,544
  • 2
  • 30
  • 39
3

"winston": "^3.0.0"

function createAppLogger() {
  const { combine, timestamp, printf, colorize } = format;

  return createLogger({
    level: 'info',
    format: combine(
      colorize(),
      timestamp(),
      printf(info => {
        return `${info.timestamp} [${info.level}] : ${JSON.stringify(info.message)}`;
      })
    ),
    transports: [new transports.Console()]
  });
}

Output:

2018-08-11T13:13:37.554Z [info] : {"data":{"hello":"Hello, World"}}

Lin Du
  • 88,126
  • 95
  • 281
  • 483
2

On "winston": "^3.2.1"

This is works great for me

const {createLogger, format} = require('winston');

// instantiate a new Winston Logger with the settings defined above
var logger = createLogger({

    format: format.combine(
      format.timestamp(),
      // format.timestamp({format:'MM/DD/YYYY hh:mm:ss.SSS'}),
      format.json(),
      format.printf(info => {
        return `${info.timestamp} [${info.level}] : ${info.message}`;
      })
  ),
  transports: [
    new winston.transports.File(options.file),
    new winston.transports.Console(options.console)
  ],
  exitOnError: false, // do not exit on handled exceptions
});
Gajen Sunthara
  • 4,470
  • 37
  • 23
0
winston.format.printf(
    info => `${info.timestamp} ${info.level}: ${JSON.stringify(info.message, null, 2)}`))

will pretty print the json object

m0tive
  • 2,796
  • 1
  • 22
  • 36
sohel
  • 1