How to Avoid Printing Empty Brackets When MDC Values Are Missing in Log4j2? - Stack Overflow

admin2025-05-01  1

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?

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?

Share Improve this question asked Jan 2 at 18:02 Rahul vermaRahul verma 3142 silver badges12 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 0

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.

转载请注明原文地址:http://www.anycun.com/QandA/1746103817a91719.html