Is it possible to let log4j output its logging in JSON format by only altering the log4j.properties.xml
configuration file?
I make use of an old application tha
just use buildin PatternLayout is ok:
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.encoding=UTF-8
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern={"debug_level":"%p","debug_timestamp":"%d{ISO8601}","debug_thread":"%t","debug_file":"%F", "debug_line":"%L","debug_message":"%m"}%n
will out put like:
{
"debug_level" : "INFO",
"debug_timestamp" : "2016-05-26 16:37:08,938",
"debug_thread" : "main",
"debug_file" : "TestLogOutPut.java",
"debug_line" : "316",
"debug_message" : "hello i am a log message"
}
this is official JSON layout
https://github.com/logstash/log4j-jsonevent-layout
1) Add maven dependency https://mvnrepository.com/artifact/net.logstash.log4j/jsonevent-layout
<dependency>
<groupId>net.logstash.log4j</groupId>
<artifactId>jsonevent-layout</artifactId>
<version>1.7</version>
</dependency>
2) Add configuration to your log4j.properties
file
log4j.rootCategory=WARN, RollingLog
log4j.appender.RollingLog=org.apache.log4j.DailyRollingFileAppender
log4j.appender.RollingLog.Threshold=TRACE
log4j.appender.RollingLog.File=api.log
log4j.appender.RollingLog.DatePattern=.yyyy-MM-dd
log4j.appender.RollingLog.layout=net.logstash.log4j.JSONEventLayoutV1
I used logback.xml with below pattern
<appender name="Console"
class="ch.qos.logback.core.ConsoleAppender">
<layout class="ch.qos.logback.classic.PatternLayout">
<Pattern>
{"level":"%p","timestamp":"%d{ISO8601}","thread":"%t","file":"%F", "line":"%L","message":"%m"}%n
</Pattern>
</layout>
</appender>
and it generates logs in json format. I am using log4j which comes with springboot dependencies.
{"level":"INFO","timestamp":"2020-09-22 15:26:38,354","thread":"main","file":"StartupInfoLogger.java", "line":"55","correlationId":"","message":"Starting Application on XX with PID 88794 (/Users/Documents/target/classes started by xxx in /Users/Documents)"}
Yes It is possible. Take a look at this link It can generate
{
"timestamp":1352412458890,
"date":"Nov 8, 2012 10:07:38 PM",
"hostname":"michael1",
"username":"michael",
"level":"INFO",
"thread":"main",
"classname":"uk.me.mjt.log4jjson.SimpleJsonLayoutTest",
"filename":"SimpleJsonLayoutTest.java",
"linenumber":25,
"methodname":"testDemonstration",
"message":"Example of some logging"
}