在某些情况下动态更改日志条目模式
Change log entry pattern dynamically on some condition
在我的 Java 应用程序中,Logback 用作日志记录框架。使用以下模式配置的附加程序(简化):
[CORR=%X{CORR}] [MSG=%msg]%n
可以看出,CORR
值取自 MDC
。日志条目示例:
[CORR=12342314] [MSG=Some message]
有些情况下属性未存储在 MDC
中,因此日志条目如下所示:
[CORR=] [MSG=Some message]
但应该是:
[MSG=Some message]
如果 MDC
中不存在相应的值而不创建自定义 LayoutBase
实现,是否有任何方法可以完全摆脱模式的 [CORR=]
部分?
我正在尝试配置评估器:
<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 应用程序中,Logback 用作日志记录框架。使用以下模式配置的附加程序(简化):
[CORR=%X{CORR}] [MSG=%msg]%n
可以看出,CORR
值取自 MDC
。日志条目示例:
[CORR=12342314] [MSG=Some message]
有些情况下属性未存储在 MDC
中,因此日志条目如下所示:
[CORR=] [MSG=Some message]
但应该是:
[MSG=Some message]
如果 MDC
中不存在相应的值而不创建自定义 LayoutBase
实现,是否有任何方法可以完全摆脱模式的 [CORR=]
部分?
我正在尝试配置评估器:
<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
正则表达式,因此被空字符串替换。