[英]Using log4j2, how to log key value pairs
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.
在PatternLayout中是否支持使用log4j2.xml为log_level,class_name,event_id等线程中的静态字段执行此操作。
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" 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-ac7c2bdac578 “app =”Test App“severity =”info“action =”loading sfor文件处理“desc =”道具被读取并加载“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"
. 您可以使用MapMessage ,它受PatternLayout的
map
(或K
)转换模式支持:示例布局模式为"%-5p [%t]: %m %map%n"
。
Logging a MapMessage looks like this: Map<String,String> myMap = getMyMap(); Logger.debug(new MapMessage(myMap));
记录MapMessage如下所示:
Map<String,String> myMap = getMyMap(); Logger.debug(new MapMessage(myMap));
Map<String,String> myMap = getMyMap(); Logger.debug(new MapMessage(myMap));
Another way to do this is to use the ThreadContext map. 另一种方法是使用ThreadContext映射。 This is supported by the
mdc
(or X
) conversion pattern of PatternLayout. 这受到PatternLayout的
mdc
(或X
)转换模式的支持。 Example pattern: "%-5p [%t]: %m %mdc%n"
. 示例模式:
"%-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. 一种常见的用法是在用户登录时将用户ID放在线程上下文映射中,并在该线程发出的所有日志消息中显示此用户ID,直到用户注销为止。
Instead of logging the whole map you can also log specific keys only by specifying the key in the layout pattern: eg "%-5p [%t]: %m %mdc{userID}%n"
. 您也可以仅通过在布局模式中指定键来记录特定键,而不是记录整个映射:例如
"%-5p [%t]: %m %mdc{userID}%n"
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.