I am using Log4j2 for logging in my application, and I include MDC (ThreadContext) values in the log pattern to track contextual information. My current log pattern looks like this:
property.LOG_PATTERN=%d{yyyy-MM-dd HH:mm:ss.SSS} [%X{customer.name}] [%X{correlation.id}] %5p [%t] %c{1.} : %m%n
When request.log.customer.name or request.log.correlation.id is not present in the ThreadContext, the output includes empty brackets ([]), like this:
2025-01-02 10:15:30.123 [] [] INFO [main] MyClass : This is a log message
I want to avoid printing the empty brackets when these MDC keys are not set. For example, if customer.name and correlation.id are missing, the output should look like this:
2025-01-02 10:15:30.123 INFO [main] MyClass : This is a log message
And if only one key is present, it should display only that key with brackets:
2025-01-02 10:15:30.123 [customer1] INFO [main] MyClass : This is a log message
How can I achieve this behavior in Log4j2?
There is a %notEmpty{...}
pattern that does exactly what you want. Just use:
%d{yyyy-MM-dd HH:mm:ss.SSS} %notEmpty{[%X{customer.name}] }%notEmpty{[%X{correlation.id}] }%5p [%t] %c{1.} : %m%n
as pattern.