Log4j2 appending values to a pattern

Viewed 73

I have a interceptor that gets some information about a request, that has been made, and I would like to append that information to a Log4j2 pattern.

For example: I have a base pattern of :

{"foo": "bar"}

Then in the interceptor I find "requestParam" : "word" and "remoteAddress" : "0.0.0.0"

I like the end result to be {"foo": "bar", "requestParam" : "word", "remoteAddress" : "0.0.0.0"}

However next intercepted request might have the same data except for one more additional field.

So it would look something like this {"foo": "bar", "requestParam" : "word", "remoteAddress" : "0.0.0.0", "key": "value"}

I have tried to use ScriptPatternSelector but it does not let you append but just select between different patterns.

Is what I am trying to do even achievable in log4j2?

1 Answers

In your interceptor add your data using ThreadContext.put(key, value). In your pattern layout you can then either specify to print all ThreadContext items or specify the items you want printed using either the %X converter or the MDC Lookup - ${ctx:key}. Your interceptor should then call ThreadContext.clearMap() at the end of the request so the data does not bleed into the next request.

Related