gpt4 book ai didi

java - JSONLayout 时将 json 对象添加到 log4j2

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:49:45 26 4
gpt4 key购买 nike

我将用 JSONLayout 显示 log4j2与消息上的对象相同。例如我的配置是:

cat log4j2.xml

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="INFO">
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
</Console>
<File name="Json" fileName="/home/jeus/log/loggerjson/main.log" bufferedIO="true" advertiseURI="file://home/jeus/log/loggerjson/main1.log" advertise="true">
<JSONLayout compact="true" locationInfo="true" complete="false" eventEol="true" properties="true" propertiesAsList="true"/>
</File>
</Appenders>
<Loggers>
<Root level="info">
<AppenderRef ref="Json"/>
</Root>
</Loggers>

我的输出:

cat /home/jeus/log/loggerjson/main.log

{
"timeMillis":1502359773290,
"thread":"main",
"level":"INFO",
"loggerName":"com.jeus.logger.json.loggerjson.Main",
"message":"This message is a raw",
"endOfBatch":false,
"loggerFqcn":"org.apache.logging.log4j.spi.AbstractLogger",
"contextMap":[ ],
"threadId":1,
"threadPriority":5,
"source":{
"class":"com.jeus.logger.json.loggerjson.Main",
"method":"main",
"file":"Main.java",
"line":61
}
}

我添加了一个 json 对象来记录但不在消息中显示 json 对象并用 \" 字符显示它

JSON object:

{"line_id": 12,"play_name":"Jeus"}

my code to log:

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class Main {

private static final Logger LOGGER = LogManager.getLogger(Main.class);

public static void main(String[] args) {


String message = "{\"line_id\": 12,\"play_name\": \"Jeus\"}";
LOGGER.info(message);

}
}

输出是:

{  
"timeMillis":1502361394238,
"thread":"main",
"level":"INFO",
"loggerName":"com.jeus.logger.json.loggerjson.Main",
"message":"{\"line_id\": 12,\"play_name\": \"Jeus\"}",
"endOfBatch":false,
"loggerFqcn":"org.apache.logging.log4j.spi.AbstractLogger",
"contextMap":[

],
"threadId":1,
"threadPriority":5,
"source":{
"class":"com.jeus.logger.json.loggerjson.Main",
"method":"main",
"file":"Main.java",
"line":62
}
}

但我会将消息显示为 json 对象,与此相同:

 "message":{"line_id": 12,"play_name":"Jeus"},

最佳答案

这似乎与内置的 JsonLayout 无关。无论我尝试什么,它都只是在字段上执行 toString 而不是正确地序列化它。

一种解决方案是使用 PatternLayout 并将其格式化为 JSON。

log4j.appender.frontEndAudit.layout=org.apache.log4j.PatternLayout
log4j.appender.frontEndAudit.layout.ConversionPattern={"timestamp":
"%d{MM/dd/yyyy HH:mm:ss:SSSS}", "class": "%C", "file": "%F", "level" :
"%5p", "line_number" : "%L", "logger_name": "frontEndAuditLog", "mdc":
"ipAddress": "%X{ipAddress}", "requestId":"%X{requestId}",
"sessionId":"%X{sessionId}"}, "message": %m, "method": "%M",
"source_host":"%X{sourceHost}", "thread_name": "%t" }%n

这是用于 log4j1,但同样的概念也适用于 log4j2

关于java - JSONLayout 时将 json 对象添加到 log4j2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45611509/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com