Using log4j2, how to log key value pairs

烈酒焚心 提交于 2019-12-05 01:56:59

问题


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"


回答1:


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



来源:https://stackoverflow.com/questions/24293213/using-log4j2-how-to-log-key-value-pairs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!