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
logback-local.xml
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"
}
SLF4J supports popular logging frameworks, namely log4j, java. util. logging, Simple logging and NOP. The logback project supports SLF4J natively.
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.
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 ...
toJsonMap()
to change names of the keys addCustomDataToJsonMap()
to add other key:value pairs to the log eventMore details on Logback JSON extensions here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With