8

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"
}
glytching
  • 44,936
  • 9
  • 114
  • 120
Deepboy
  • 523
  • 3
  • 16
  • 28

1 Answers1

8

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.

glytching
  • 44,936
  • 9
  • 114
  • 120