Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write slf4j-over-logback logs as JSON

I have the below logging statements in my code.

import org.slf4j.Logger;

public class MySampleClass {

private static final Logger logger = LoggerFactory.getLogger(MySmapleClass.class);

    public void mySampleMethod(List<String> userID) {
        logger.debug("userRuntimeId =" + userId);
        .
        .
        .
        Business Logic
        .
        .

    }
}

My log configs are available in: logback-common.xml enter image description here

logback-local.xml enter image description here

This prints my logs as given below,

2019-02-25 16:27:45,460 | DEBUG | [fileTaskExecutor-2] | [a.abc.mySampleApp.handlers.userRecordHandler] | [MY_SAMPLE_APP] | [Vijay-20190225-162738.trigger] | [] | userRuntimeId = 3051aa39-2e0a-11e9-bee3-e7388cjg5le0

I want to print the logs as JSON. How do I do it?

Sample JSON format I expect:

{
timestamp="2019-02-25 16:27:45,460" ,
level="DEBUG",
triggerName="fileTaskExecutor-2",
className="a.abc.mySampleApp.handlers.userRecordHandler",
appName="MY_SAMPLE_APP",
userRuntimeId="3051aa39-2e0a-11e9-bee3-e7388cjg5le0"
}
like image 580
Deepboy Avatar asked Feb 28 '19 21:02

Deepboy


People also ask

Does slf4j support Logback?

SLF4J supports popular logging frameworks, namely log4j, java. util. logging, Simple logging and NOP. The logback project supports SLF4J natively.

Does log4j support JSON format?

json provided by the log4j-layout-template-json artifact, which contains the following predefined event templates: EcsLayout. json described by the Elastic Common Schema (ECS) specification.


1 Answers

You can use logback-contrib's JsonLayout inside any Logback appender. For example:

<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
    <layout class="ch.qos.logback.contrib.json.classic.JsonLayout">
        <jsonFormatter class="ch.qos.logback.contrib.jackson.JacksonJsonFormatter">
            <prettyPrint>false</prettyPrint>
        </jsonFormatter>
        <timestampFormat>yyyy-MM-dd' 'HH:mm:ss.SSS</timestampFormat>
        <appendLineSeparator>true</appendLineSeparator>
        <includeContextName>false</includeContextName>
    </layout>
</appender>

With that configuration the following log invocation ...

logger.info("hello!");

... will emit:

{
  "timestamp" : "2019-03-01 08:08:32.413",
  "level" : "INFO",
  "thread" : "main",
  "logger" : "org.glytching.sandbox.logback.LogbackTest",
  "message" : "hello!"
}

That's quite close to your desired output and JsonLayout is extensible so you could ...

  • Override toJsonMap() to change names of the keys
  • Implement addCustomDataToJsonMap() to add other key:value pairs to the log event

More details on Logback JSON extensions here.

like image 85
glytching Avatar answered Oct 07 '22 15:10

glytching