Log4j2将值附加到模式

huangapple go评论69阅读模式
英文:

Log4j2 appending values to a pattern

问题

我有一个拦截器,可以获取有关已进行的请求的一些信息,我想将该信息附加到Log4j2模式中。

例如:
我有一个基本模式:

    

{ "foo" : "bar" }

然后在拦截器中,我找到了 "requestParam" : "word" 和 "remoteAddress" : "0.0.0.0"。

我希望最终的结果是 { "foo" : "bar", "requestParam" : "word", "remoteAddress" : "0.0.0.0" }

然而,下一个被拦截的请求可能具有相同的数据,除了多了一个附加字段。

因此,它可能看起来像这样 { "foo" : "bar", "requestParam" : "word", "remoteAddress" : "0.0.0.0", "key" : "value" }

我已经尝试使用 ScriptPatternSelector,但它不允许您附加,只能在不同的模式之间进行选择。

我所尝试做的事情在log4j2中是否可行?

英文:

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

得分: 1

在你的拦截器中,使用ThreadContext.put(key, value)添加你的数据。在你的模式布局中,你可以选择打印所有ThreadContext项目,或者使用%X转换器或MDC查找(${ctx:key})来指定要打印的项目。然后,你的拦截器应该在请求结束时调用ThreadContext.clearMap(),以便数据不会泄漏到下一个请求中。

英文:

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.

huangapple
  • 本文由 发表于 2020年8月27日 18:24:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/63613984.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定