8

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 ?

Tanmoy
  • 1,409
  • 3
  • 13
  • 14

4 Answers4

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>}

igreenfield
  • 1,618
  • 19
  • 36
3

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>}

bnorm
  • 908
  • 1
  • 7
  • 14
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

Cody S
  • 4,744
  • 8
  • 33
  • 64
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.

Vignesh Shiv
  • 1,129
  • 7
  • 22