在我的 Java 应用程序中,Logback 用作日志记录框架。附加程序配置为以下模式(简化):
[CORR=%X{CORR}] [MSG=%msg]%n
正如我们所见,CORR
值取自 MDC
。日志条目示例:
[CORR=12342314] [MSG=Some message]
在某些情况下,属性未存储在 MDC
中,因此日志条目如下所示:
[CORR=] [MSG=Some message]
但应该是:
[MSG=Some message]
如果MDC
中不存在相应的值,有没有办法完全摆脱模式的这个[CORR=]
部分,而不创建自定义的LayoutBase
实现?
我正在尝试配置评估器:
<evaluator name="DISPLAY_CORR_EVAL">
<expression>((String) mdc.get("CORR")) != null</expression>
</evaluator>
但不知道如何在我的案例中使用它。
最佳答案
借助Logback replace(p){r, t}
转换词解决了问题:
Replaces occurrences of 'r', a regex, with its replacement 't' in the string produces by the sub-pattern 'p'. For example, "%replace(%msg){'\s', ''}" will remove all spaces contained in the event message.
The pattern 'p' can be arbitrarily complex and in particular can contain multiple conversion keywords. For instance, "%replace(%logger %msg){'.', '/'}" will replace all dots in the logger or the message of the event with a forward slash.
我的模式现在如下所示:
%replace([CORR=%X{CORR}]){'\[CORR=\]', ''}[MSG=]%n
当 CORR
为空时,[CORR=]
匹配 r
正则表达式,从而被空字符串替换。
关于java - 在某些情况下动态更改日志条目模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36173378/