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