首页 > 解决方案 > 使用 Logstash 编码器记录异常时如何包含 mdc 键

问题描述

我有logback-spring.xml文件,其中有 json 控制台附加程序:

我包括 mdc 密钥requestId

但是,当记录运行时异常时,此 requestId 会丢失。当出现异常时,有没有办法可以在日志中打印 requestId?

<configuration>

    <appender name="jsonConsoleAppender" class="ch.qos.logback.core.ConsoleAppender">
        <encoder class="net.logstash.logback.encoder.LogstashEncoder">
            <fieldNames>
                <timestamp>log_datetime</timestamp>
                <thread>thread</thread>
                <logger>[ignore]</logger>
                <version>[ignore]</version>
                <levelValue>[ignore]</levelValue>
                <callerClass>class_name</callerClass>
                <callerMethod>method_name</callerMethod>
                <callerFile>[ignore]</callerFile>
                <callerLine>line_num</callerLine>
            </fieldNames>
            <includeMdcKeyName>requestId</includeMdcKeyName>
            <timestampPattern>yyyy-MM-dd HH:mm:ss.SSS</timestampPattern>
            <includeCallerData>true</includeCallerData>
            <throwableConverter class="net.logstash.logback.stacktrace.ShortenedThrowableConverter">
                <maxDepthPerThrowable>30</maxDepthPerThrowable>
                <maxLength>2048</maxLength>
                <shortenedClassNameLength>20</shortenedClassNameLength>
                <exclude>sun\.reflect\..*\.invoke.*</exclude>
                <exclude>net\.sf\.cglib\.proxy\.MethodProxy\.invoke</exclude>
                <rootCauseFirst>true</rootCauseFirst>
                <inlineHash>true</inlineHash>
            </throwableConverter>
        </encoder>
    </appender>

    <springProfile name="!local">
        <root level="INFO">
            <appender-ref ref="jsonConsoleAppender"/>
        </root>
    </springProfile>

</configuration>

标签: javaspringlogginglogstashspring-logback

解决方案


推荐阅读