我已经在不同类型的项目中使用过log4j,并且有一些使用log4j2的经验。所有实现都使用默认的附加器和布局。目前,我需要写一个应用程序写在json格式。因此,我通过设置一个非常简单的log4j2记录器来尝试log4j2 JSONLayout布局。
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>
导致类似于的日志条目;
, {
"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
}
我需要的是像这样的JSON格式的日志;
, {
"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" }
}
在log4j2 JSONLayout中可以这样做吗?或者有没有其他布局可以用来获得这种格式?
发布于 2021-07-28 05:19:52
我知道这是一个老生常谈的问题,但我认为还有更好的方法。
您应该使用JSON Template Layout。
然后,您将能够使用如下模板配置您的JsonLayout:
{
"mdc": {
"$resolver": "mdc"
},
"exception": {
"exception_class": {
"$resolver": "exception",
"field": "className"
},
"exception_message": {
"$resolver": "exception",
"field": "message"
},
"stacktrace": {
"$resolver": "exception",
"field": "stackTrace",
"stackTrace": {
"stringified": true
}
}
},
"line_number": {
"$resolver": "source",
"field": "lineNumber"
},
"class": {
"$resolver": "source",
"field": "className"
},
"@version": 1,
"source_host": "${hostName}",
"message": {
"$resolver": "message",
"stringified": true
},
"thread_name": {
"$resolver": "thread",
"field": "name"
},
"@timestamp": {
"$resolver": "timestamp"
},
"level": {
"$resolver": "level",
"field": "name"
},
"file": {
"$resolver": "source",
"field": "fileName"
},
"method": {
"$resolver": "source",
"field": "methodName"
},
"logger_name": {
"$resolver": "logger",
"field": "name"
}
}
使用模板有许多可用的配置。
有关它的更多信息,请单击此处:
https://logging.apache.org/log4j/2.x/manual/json-template-layout.html
https://stackoverflow.com/questions/39647900
复制相似问题