gpt4 book ai didi

java - log4j 消息转 json

转载 作者:行者123 更新时间:2023-11-30 02:35:03 24 4
gpt4 key购买 nike

我有一条消息,比如 delay=1, name=Ash,我想使用 log4j2 进行记录。我希望我的日志文件的每一行都是 json 格式

{"@timestamp": 1234, "delay"=1, "name"="Ash"}

@timestamp 字段是记录器生成的时间戳,而 delayname 字段是消息字段。

有办法做到这一点吗?通过使用 JsonLayout,我知道我可以以 json 格式获取每个记录的输出,但我仍然没有找到一种方法来操作日志消息,以便我可以将其不同部分放在不同的字段中。

最佳答案

您可以使用 log4j2 JSONLayout 来完成此操作。

  • 首先你必须指定 jsonlayout

示例:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<JSONLayout compact="true" eventEol="true" properties="true"/>
</Console>
</Appenders>
<Loggers>
<Root level="info">
<AppenderRef ref="Console"/>
</Root>
</Loggers>
</Configuration>

这里如果设置compact = false,json将以prity格式打印

  • 其次,您可以ThreadContext将值作为键值对。

示例:

for (int i = 0; i < 5; i++) {
ThreadContext.clearAll();
ThreadContext.put("delay", String.valueOf(i));
ThreadContext.put("name", "Ash " + i);
LOGGER.info("Testing ", "k1", "v1", "k2", "v2");
}

这里ThreadContext保留所有键值对,直到清除。

输出:

{"timeMillis":1491819918389,"thread":"main","level":"INFO","loggerName":"com.ashraful.ilpexp.LogTest","message":"Testing ","endOfBatch":false,"loggerFqcn":"org.apache.logging.log4j.spi.AbstractLogger","contextMap":{"delay":"0","name":"Ash 0"},"threadId":1,"threadPriority":5}
{"timeMillis":1491819918504,"thread":"main","level":"INFO","loggerName":"com.ashraful.ilpexp.LogTest","message":"Testing ","endOfBatch":false,"loggerFqcn":"org.apache.logging.log4j.spi.AbstractLogger","contextMap":{"delay":"1","name":"Ash 1"},"threadId":1,"threadPriority":5}
{"timeMillis":1491819918504,"thread":"main","level":"INFO","loggerName":"com.ashraful.ilpexp.LogTest","message":"Testing ","endOfBatch":false,"loggerFqcn":"org.apache.logging.log4j.spi.AbstractLogger","contextMap":{"delay":"2","name":"Ash 2"},"threadId":1,"threadPriority":5}
{"timeMillis":1491819918505,"thread":"main","level":"INFO","loggerName":"com.ashraful.ilpexp.LogTest","message":"Testing ","endOfBatch":false,"loggerFqcn":"org.apache.logging.log4j.spi.AbstractLogger","contextMap":{"delay":"3","name":"Ash 3"},"threadId":1,"threadPriority":5}
{"timeMillis":1491819918505,"thread":"main","level":"INFO","loggerName":"com.ashraful.ilpexp.LogTest","message":"Testing ","endOfBatch":false,"loggerFqcn":"org.apache.logging.log4j.spi.AbstractLogger","contextMap":{"delay":"4","name":"Ash 4"},"threadId":1,"threadPriority":5}

关于java - log4j 消息转 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43319107/

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