简体   繁体   中英

Log4j2 appending values to a pattern

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM