Deepboy
Deepboy

Reputation: 531

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"
}

Upvotes: 8

Views: 20095

Answers (2)

vorburger
vorburger

Reputation: 3938

You could also just use Penna, which is an implementation of the Log4j API which directly (and only) emits JSON; if that's all you need, consider using it instead of Logback. (Your library and application code still logs using the Log4j API.?

Upvotes: 0

glytching
glytching

Reputation: 47965

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.

Upvotes: 8

Related Questions