How do I print a key/value pair on a log4j entry only if the value is set on MDC?
For example, I currently have the following pattern:
%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - client=%X{client} %m%n
I'd like to print the "client=" part only if there is a value on MDC for this key.
For example, when starting my program, there will be no client logged in, so logs would be recorded using this pattern:
%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
However, after the client has logged in (and after I have set the MDC with a "client" key), I need to print it using the following:
%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - client=%X{client} %m%n
Is there such "conditional pattern" on log4j?
Thank you
A Mapped Diagnostic Context, or MDC in short, is an instrument for distinguishing interleaved log output from different sources. Log output is typically interleaved when a server handles multiple clients near-simultaneously.
MDC in Log4j allows us to fill a map-like structure with pieces of information that are accessible to the appender when the log message is actually written. The MDC structure is internally attached to the executing thread in the same way a ThreadLocal variable would be.
To recall, a conversion pattern specifies how log messages are formatted, using a combination of literals, conversion characters and format modifiers. Consider the following pattern: log4j.appender.ConsoleAppender.layout.ConversionPattern=[%-5p] %d %c - %m%n.
The Thread Context Map allows any number of items to be added and be identified using key/value pairs. The Thread Context Stack allows one or more items to be pushed on the Stack and then be identified by their order in the Stack or by the data itself.
There is a %notEmpty
pattern in Log4j2 which allows you to achieve exactly this.
%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %notEmpty{client=%X{client} }%m%n
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With