我想以 log4j2 Json 格式记录 2 个自定义字段,其中一个具有固定值,另一个来自 ThreadContext。我正在使用 JsonTemplateLayout,并且仅当字段具有某些值时才想打印字段,否则从日志中忽略它们。
<?xml version="1.0" encoding="UTF-8"?>
<Configuration>
<Appenders>
<Console name="console" target="SYSTEM_OUT">
<JsonTemplateLayout eventTemplateUri="classpath:JsonLayout.json">
<EventTemplateAdditionalField key="myApp" value="MYAPPLICATION" />
<EventTemplateAdditionalField key="customKey1" value="$${ctx:customKey1:-}" />
</JsonTemplateLayout>
</Console>
</Appenders>
<Loggers>
<Root level="info" additivity="false">
<AppenderRef ref="console" />
</Root>
</Loggers>
</Configuration>
在这里,我仅为应用程序中的一些特定日志语句设置 customKey1 的值,对于其余日志语句,将不会设置此 customKey1 。因此,我的期望是避免以日志格式打印 customKey1,而仅在未为此键设置线程上下文时打印日志中的默认字段和 myApp 字段。
版本信息:
"org.springframework.boot:spring-boot-starter-log4j2:2.7.18" "org.apache.logging.log4j:log4j-layout-template-json:2.21.1"
使用 JsonLayout 时,只有在 threadcontext 中设置了相同的值时,customKey1 才可见;但使用 JsonTemplateLayout,即使未设置 customKey1,customKey1 仍然可见。
<EventTemplateAdditionalField key="customKey1" value="$${ctx:customKey1:-}" />
不要使用查找。更喜欢原生 JTL 解析器:
<EventTemplateAdditionalField key="customKey1"
format="JSON"
value='{"$resolver": "mdc", "key": "customKey1"}'/>
如果发现
customKey1
字段为空白(即空或为空),则会丢弃该字段。