Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way in nodejs to print log4js output in JSON format?

Tags:

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.

like image 695
Pravin Bhapkar Avatar asked Mar 21 '16 12:03

Pravin Bhapkar


People also ask

Is Log4J and Log4JS the same?

The answer is simple: Log4JS and Log4J share only a similar name and API. The codebases are entirely different (and written in different languages). The vulnerability of Log4J does not apply obviously to Log4JS.

Can we use Log4J in node JS?

log4js-node. This is a conversion of the log4js framework to work with node. I started out just stripping out the browser-specific code and tidying up some of the javascript to work better in node. It grew from there.

Does Winston logger use Log4J?

While it's not as popular or highly rated as Winston, Log4js has all the qualities I look for in a logger. It also has a similar feel to log4j, making it a popular choice for Java developers who have transitioned to Node. js.


1 Answers

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');
like image 196
troy Avatar answered Oct 11 '22 14:10

troy