使用log4j2,如何记录键值对[英] Using log4j2, how to log key value pairs

本文是小编为大家收集整理的关于使用log4j2,如何记录键值对的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

我需要使用键值对创建日志,如下所示.是否有任何支持在log_level,class_name,event_id等线程中使用log4j2.xml.

等线程中的静态字段.

样本日志:

2014-06-18 11:57:46,719 log_level =" info" class_name =" com.abc.dgl.app:main(158)" name ="应用开始事件" event_id =" b88f7ea0-4cb1-438f-a728-a728-ac7c2bdac578已读取并加载了加载的sfor文件处理" desc =" props ="成功"原因=" abc" transaction_id =" b88f7ea0-4cb1-438f-a728-ac7c2bdac578"

>

推荐答案

是的,这是可能的.

您可以使用 mapmessage ,由map(或K) datternlayout :一个示例布局模式将为"%-5p [%t]: %m %map%n".

记录mapmessage看起来像这样:Map<String,String> myMap = getMyMap(); Logger.debug(new MapMessage(myMap));

另一种方法是使用 threadContext 地图.这是由模式下的mdc(或X)转换模式支持的.示例模式:"%-5p [%t]: %m %mdc%n". 一个常见的用法是将用户登录时将用户ID放在线程上下文映射中,并在该线程发出的所有日志消息中显示此用户ID,直到用户登录为止.

而不是记录整个地图,您还可以通过在布局模式中指定键来记录特定键:例如"%-5p [%t]: %m %mdc{userID}%n".

其他推荐答案

是.使用%kvp作为模式layout中的模式.

不幸的是,它不是非常可配置的. 根据 source .

本文地址:https://www.itbaoku.cn/post/1574876.html

问题描述

I need to create logs with key value pairs as below. Is there any support in PatternLayout to do this for the static fields in a thread like log_level, class_name, event_id etc with the log4j2.xml.

Sample log:

2014-06-18 11:57:46,719 log_level="INFO" class_name="com.abc.dgl.App:main(158)" name="Application start event" event_id="b88f7ea0-4cb1-438f-a728-ac7c2bdac578" app="Test App" severity="info" action="loaded sfor file processing" desc="props was read and loaded" result="success" reason="abc" transaction_id="b88f7ea0-4cb1-438f-a728-ac7c2bdac578"

推荐答案

Yes, this is possible.

You can either use a MapMessage, which is supported by the map (or K) conversion pattern of PatternLayout: an example layout pattern would be "%-5p [%t]: %m %map%n".

Logging a MapMessage looks like this: Map<String,String> myMap = getMyMap(); Logger.debug(new MapMessage(myMap));

Another way to do this is to use the ThreadContext map. This is supported by the mdc (or X) conversion pattern of PatternLayout. Example pattern: "%-5p [%t]: %m %mdc%n". A common usage is putting a user ID in the Thread Context Map when a user logs in, and having this user ID shown in all log messages emitted by that thread until the user logs out.

Instead of logging the whole map you can also log specific keys only by specifying the key in the layout pattern: e.g. "%-5p [%t]: %m %mdc{userID}%n".

其他推荐答案

Yes. Use %kvp as the pattern in your PatternLayout.

Unfortunately, it isn't very configurable. This was added in 1.3.0 according to the source.