How to conditionally add text from MDC on a LOG4J pattern?

I endend up using xav's suggestion.

I removed the "client=" string from the log4j pattern and appended it everytime I added an entry to MDC. It's not the most beautiful solution but it worked great!

For example, where I otherwise would use

MDC.put("client", client.getId());

I am now using:

MDC.put("client", "client="+client.getId().toString());

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

Tags:

Log4J