1

I have log4j2-spirng.xml with this pattern layout

<PatternLayout alwaysWriteExceptions="false"      
 pattern={... &quot;userId&quot;:&quot;%X{userId}&quot;} ..." />

userId is value from MDC. In case it is null it is logged with blank value like this:

..., "userId": "", ...

Now I'm trying to move all fields from pattern layout to Json template using JsonTemplateLayout.

And in log-template I'm trying to construct same log message. Timestamp and other fields are fine no issues there. Only problem with mdc values. When values are present those are logged correctly, but when not, field is ignored and not included in log. Reading values from mdc like this

...
  "userId": {
    "$resolver": "mdc",
    "key": "userId"
  },
...

Should I apply formatting and put this "%X" somewhere or how does it works? I have to get same log as from pattern layout, with all fields and if fields is not present in MDC or null or empty still include it in log just with empty string value.

1 Answers1

0

This is the way the ThreadContextDataResolver (aka mdc) is supposed to work: if the given thread context key is not present, the JSON property is omitted.

If you want to include those properties, even if they are empty, use a PatternResolver:

"userId": {
  "$resolver": "pattern",
  "pattern": "%X{userId}"
}
Piotr P. Karwasz
  • 12,857
  • 3
  • 20
  • 43