Empty Threadcontext braces scenario handling in log4j2

1.7k Views Asked by At

I am trying to migrate to log4j2. In RollingFile Appender I am adding as below:

<PatternLayout>
    <pattern>[%d{MM/dd/yy HH:mm:ss:SSS z}] %-18.18t %-35.35c{1} %-5p (%F:%L) %m \t %x %n</pattern>
</PatternLayout>

We know that %x is for printing stack elements to end of the every logger statement.

Now if my stack is empty initially, it is giving me the empty braces as below.

[01/10/17 12:17:37:116 IST] main               Example2                            WARN  (Example2.java:52) 10 is the number     [] 

[01/10/17 12:17:37:116 IST] main Example2 WARN (Example2.java:52) 10 is the number []

So how do I handle this empty stack scenario ?

2

There are 2 best solutions below

6
On

You can use PatternLayout's notEmpty{pattern} pattern converter:

This outputs the result of evaluating the pattern if and only if all variables in the pattern are not empty.

For example:

%notEmpty{[%x]}

Aliases: variablesNotEmpty{pattern}, varsNotEmpty{pattern}, notEmpty{pattern}

0
On

You can use %equals{pattern}{test}{substitution} from https://logging.apache.org/log4j/2.x/manual/layouts.html#PatternLayout

For example -

%equals{%x}{[]}{}

This will replace [] with empty string. Worked for me.