在 logback 中检索 MDC 值

Retrieve MDC values in logback

我正在尝试在 stdout 和 logstash 中记录 MDC 值。

<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%-5level [%thread] %logger{0}: %msg -someName=%X{mdcFieldKey} %n</pattern>
            <charset>utf8</charset>
        </encoder>
    </appender>

    <appender name="logstash" class="net.logstash.logback.appender.LogstashTcpSocketAppender">
        <destination>kibanaurl:port</destination>
        <encoder class="net.logstash.logback.encoder.LogstashEncoder">
            <customFields>
                {
                "application-name":"${spring.application.name}",
                "someName":"${mdcFieldKey}",
                "dummyName":"dummyValue"
                }
            </customFields>
            <provider class="net.logstash.logback.composite.loggingevent.ArgumentsJsonProvider"/>
        </encoder>
    </appender>

Java代码:

MDC.put("mdcFieldKey", "value to be displayed in kibana");

STDOUT 附加程序在 kibana 上正确显示 mdc 值,但对于 logstash 附加程序,我看到 someName_IS_UNDEFINED。硬编码 dummyname 也能正确显示。

为什么 logstash 自定义字段中未填充 mdc 值?

在此处查看 https://github.com/logstash/logstash-logback-encoder#mdc-fields

添加行 <includeMdcKeyName>mdcFieldKey</includeMdcKeyName> 如下是一个选项。在这种情况下,字段名称将与 mdc 键相同

<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%-5level [%thread] %logger{0}: %msg -someName=%X{mdcFieldKey} %n</pattern>
            <charset>utf8</charset>
        </encoder>
    </appender>

    <appender name="logstash" class="net.logstash.logback.appender.LogstashTcpSocketAppender">
        <destination>kibanaurl:port</destination>
        <encoder class="net.logstash.logback.encoder.LogstashEncoder">
            <includeMdcKeyName>mdcFieldKey</includeMdcKeyName>
            <customFields>
                {
                "application-name":"${spring.application.name}",
                "dummyName":"dummyValue"
                }
            </customFields>
            <provider class="net.logstash.logback.composite.loggingevent.ArgumentsJsonProvider"/>
        </encoder>
    </appender>