本文介绍了使用log4j2,如何记录键值对的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要创建具有键值对的日志,如下所示.对于使用log4j2.xml的log_level,class_name,event_id等线程中的静态字段,PatternLayout中是否提供支持?

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.

示例日志:

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 =测试App"严重性="info" action =已加载sfor文件处理",并已读取并加载了desc ="props",结果为成功",原因为"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="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"

推荐答案

是的,这是可能的.

您可以使用 MapMessage ,由 PatternLayout :示例布局模式为"%-5p [%t]: %m %map%n".

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看起来像这样:Map<String,String> myMap = getMyMap(); Logger.debug(new MapMessage(myMap));

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

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

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.

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

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".

这篇关于使用log4j2,如何记录键值对的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

查看更多