How to set a default value against an MDC key in log4j 2?
Asked Answered
S

4

9

As in log4j we have an option to set a default value against an MDC key like this - mdc{key:-defaultVal}

Do we have something similar in log4j 2 ?

Superintendent answered 23/11, 2016 at 15:51 Comment(0)
A
6

Looking in MdcPatternConverter it does not have support for default value.

There is open Jira ticket on that Tickt

I find that you can also use this: ${ctx:<key>:-<default_value>}

Alexanderalexandr answered 6/4, 2017 at 10:28 Comment(3)
only default value is printing but not printing the values @AlexanderalexandrAciniform
Which version you are using and how you set the MDC?Alexanderalexandr
I'm using ThreadContext with spring boot log4j2 2.2.5 version but when I used double dollers like this $${ctx:<key>:-<default_value>} it started printing dynamic values as well with default when it's empty or nullAciniform
C
4

While there is no way to set a default with the %X pattern, there are the %equals and %equalsIgnoreCase patterns which can be used for something equivalent.

%equals{%X{<key>}}{}{<default>}

Cartridge answered 13/7, 2018 at 20:16 Comment(0)
R
1

It seems this must have changed at some point, as it is now possible to specify default values.

If you do something like org.apache.logging.log4j.ThreadContext.put("foo", "bar"); in your code, and then, in the log4j2 pattern, specify something like

<Pattern>%-5p [%t] %d [$${ctx:foo:-baz}] %c{1} - %m%n</Pattern>

You will see [bar] in the log messages generated by the same thread that the ThreadContext call was made, and you'll see [baz] in other threads.

Please note, (h/t to @Mahender Reddy Yasa in a comment above), you are able to specify ...[${ctx:foo}]... and it will print [bar] in the correct thread, but blank in the other threads - however, and I have no idea why, if you specify ...[${ctx:foo:-baz}]..., it will always print [baz] - You must use two dollar signs for it to get the correct behavior (e.g. ...[$${ctx:foo:-baz}]...

P.S. the brackets ([]) are not necessary, this is examples from my config

Royston answered 7/6, 2022 at 20:32 Comment(0)
F
0

Offical Reference Logback link for Layout components.

X{key:-defaultVal}

If the specified Key value is null, then the default value specified after the :- operator is output.

If no default value is specified than the empty string is output.

Fishnet answered 26/12, 2018 at 16:15 Comment(1)
This is an answer for logback, but OP asked for log4j2Budweis

© 2022 - 2024 — McMap. All rights reserved.