Log JSON object with log4j JsonLayout

Viewed 3167

Hey i have a project that uses log4j and slf4j for logging. I configure the layout of the log to be JsonLayout. Is it possible to log a JSON object while keeping the json format.

For Example :

    JsonObject object = new JsonObject();
    object.addProperty("ID", 3);
    LOGGER.info("{}", object);

will output :

{
  "timeMillis" : 1496579005079,
  "thread" : "main",
  "level" : "INFO",
  "loggerName" : "Logger",
  **"message" : "{\"ID\":3}",**
  "endOfBatch" : false,
  "loggerFqcn" : "org.apache.logging.slf4j.Log4jLogger",
  "threadId" : 1,
  "threadPriority" : 5
}

While i need it to output this:

{
  "timeMillis" : 1496579005079,
  "thread" : "main",
  "level" : "INFO",
  "loggerName" : "Logger",
  **"message" : {"ID":3},**
  "endOfBatch" : false,
  "loggerFqcn" : "org.apache.logging.slf4j.Log4jLogger",
  "threadId" : 1,
  "threadPriority" : 5
}
1 Answers

There is an objectMessageAsJsonObject that should do this for you. In your log4j2.xml:

 <RollingFile name="json-log" fileName="build/log"
      filePattern="/var/log/.%d{yyyy-MM-dd}.log">
      <JSONLayout objectMessageAsJsonObject="true"/>    
 </RollingFile>
Related