5

I am trying to get output of log4js in JSON format so I can easily trace it. Is there any way that we have to set in configuration.json so output produced by log4js will be in JSON format?

Currently I am using following config.

{
 "appenders": [
{
  "category": "XXXXX",
  "type": "dateFile",
  "filename": "XXXXXXXX",
  "pattern": "-from-MM-dd",
  "layout": {
    "type": "messagePassThrough"
  }
},
{
  "category": "XXXXXXXXX",
  "type": "dateFile",
  "filename": "XXXXXXXX",
  "pattern": "-from-MM-dd",
  "layout": {
    "type": "messagePassThrough"
  }
}
 ],
"levels": {
"XXXXConfig":  "INFO",
"XXXXXjectConfig" : "INFO"
 }
}

and I got output is in following format :

DEBUG:  1458562784032 : 2016-03-21T12:19:44.4444+00:00 : Data in request: : {
"action": "XXXXXXX",
"user": {
    "username": "XXXX",
     "id" : XXXX,
    "pos" : XXXX
},
"version": 111
}

instead I want it in (Something like following structure) :

{"id" : "1458562784032", "time" : "2016-03-21T12:19:44.4444+00:00", "message" : "Data in request:", "data" : "{ "action": "XXXXXXX", "user": { "username": "XXXX", "id" : XXXX, "pos: : XXXX }, "version": 111 }" }

May be there is something I missing in config.

Thanks for helping.

Pravin Bhapkar
  • 463
  • 1
  • 5
  • 15
  • I tried a lot for that but didn't get any solution till the time, Instead I am creating log in JSON format itself and pushing it into log file. So now I have JSON logs in my log file. :) – Pravin Bhapkar Mar 22 '16 at 17:08

2 Answers2

4

There are two ways to implement this issue now, you can add your own layouts or pattern format.

Below is the sample code of adding your own layouts with JSON format

const log4js = require('log4js');

log4js.addLayout('json', function(config) {
  return function(logEvent) { return JSON.stringify(logEvent) + config.separator; }
});

log4js.configure({
  appenders: {
    out: { type: 'stdout', layout: { type: 'json', separator: ',' } }
  },
  categories: {
    default: { appenders: ['out'], level: 'info' }
  }
});

const logger = log4js.getLogger('json-test');
logger.info('this is just a test');
Akhil Ravindran
  • 126
  • 1
  • 10
troy
  • 2,145
  • 2
  • 23
  • 31
0

We can use bunyan for same purpose which logs your console log in JSON format. Here is the npm link for node : https://www.npmjs.com/package/bunyan.

Also even if you want to use log4js then create your own pattern and write log file into JSON format.

Thanks.

Pravin Bhapkar
  • 463
  • 1
  • 5
  • 15