Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

like image 418
Matheus208 Avatar asked Jul 07 '14 17:07

Matheus208


People also ask

What is MDC in Log4j?

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.

What is the use of MDC in slf4j?

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.

What is ConversionPattern in Log4j?

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.

What is thread context map?

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.


1 Answers

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 
like image 177
bnorm Avatar answered Oct 24 '22 16:10

bnorm