I have been using log4j for different kind of projects and have some experience with log4j2. All implementations used the default appender and layout. Currently i need to write a application which writes in json format. So i tried the log4j2 JSONLayout layout by setting up a very simple log4j2 logger.
public class JSONLogger {
private static final Logger LOGGER = LogManager.getLogger();
public static void main(String[] args) {
JSONLogger jsonlogger = new JSONLogger() ;
}
public JSONLogger() {
LOGGER.log(Level.FATAL, "hi mum!") ;
int val1 = 10, val2 = 11, val3 = 12;
LOGGER.log(Level.FATAL,"val1={}, val2={}, val3={}", val1, val2, val3);
}
}
jsonLoggerProperties.xml
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="DEBUG">
<Properties>
<Property name="log-path">/Users/petervannes/NetBeansProjects/JSONLogger/logfiles</Property>
</Properties>
<Appenders>
<RollingFile name="json_file_appender" fileName="${log-path}/jsonlogger.json"
filePattern="${log-path}/%d{yyyyMMdd}_jsonlogger-%i.json" >
<JSONLayout complete="true" compact="false"/>
<Policies>
<SizeBasedTriggeringPolicy size="1 KB" />
</Policies>
<DefaultRolloverStrategy max="4"/>
</RollingFile>
</Appenders>
<Loggers>
<root level="debug" additivity="false">
<AppenderRef ref="json_file_appender"/>
</root>
</Loggers>
</Configuration>
Resulting in an log entry similar to;
, {
"timeMillis" : 1474573600359,
"thread" : "main",
"level" : "FATAL",
"loggerName" : "JSONLogger",
"message" : "val1=10, val2=11, val3=12",
"contextStack" : [ "fieldName2" ],
"endOfBatch" : false,
"loggerFqcn" : "org.apache.logging.log4j.spi.AbstractLogger",
"threadId" : 1,
"threadPriority" : 5
}
What i need is to log to a JSON format like this;
, {
"DateTime" : "08/01/2016 21:33:22.334",
"level" : "FATAL",
"Summary" : "Something has gone wrong",
"ChainManager" : "Manager A",
"Optionals" : { "Key_1": "Value1",
"Key_2": "Value2" }
}
Is this possibile with the log4j2 JSONLayout or is there any other layout i can use to get this format ?