简体   繁体   English

Log4j2 将值附加到模式

[英]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.我有一个拦截器,可以获取有关已发出的请求的一些信息,我想将该信息附加到 Log4j2 模式中。

For example: I have a base pattern of :例如:我有一个基本模式:

{"foo": "bar"}

Then in the interceptor I find "requestParam" : "word" and "remoteAddress" : "0.0.0.0"然后在拦截器中我找到 "requestParam" : "word" 和 "remoteAddress" : "0.0.0.0"

I like the end result to be {"foo": "bar", "requestParam" : "word", "remoteAddress" : "0.0.0.0"}我喜欢最终结果是{"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"}所以它看起来像这样{"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.我曾尝试使用 ScriptPatternSelector,但它不允许您追加,而只是在不同的模式之间进行选择。

Is what I am trying to do even achievable in log4j2?我想要做的甚至可以在 log4j2 中实现吗?

In your interceptor add your data using ThreadContext.put(key, value).在拦截器中使用 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}.在您的模式布局中,您可以指定打印所有 ThreadContext 项目或使用 %X 转换器或 MDC 查找 - ${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.然后您的拦截器应该在请求结束时调用 ThreadContext.clearMap() 以便数据不会渗入下一个请求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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