Spring Boot 不会在异常时记录映射诊断上下文 (MDC)

Pav*_*vlo 5 logging mdc spring-boot

我需要在日志中包含映射的诊断上下文数据。应用程序构建:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.8.RELEASE</version>
    <relativePath /> <!-- lookup parent from repository -->
</parent>
Run Code Online (Sandbox Code Playgroud)

为了在日志中获取 MDC,我将其放入application.properties文件中:

logging.pattern.level=%X{mdcData}%5p
Run Code Online (Sandbox Code Playgroud)

并创建一个类

@Component
public class RequestFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        try {
            // Setup MDC data:
            String mdcData = String.format("[userId:%s | requestId:%s] ", "hello", "hello");
            MDC.put("mdcData", mdcData); //Variable 'mdcData' is referenced in Spring Boot's logging.pattern.level property
            chain.doFilter(request, response);
        } finally {
           // Tear down MDC data:
           // ( Important! Cleans up the ThreadLocal data again )
            MDC.clear();
        }
    }
...
}
Run Code Online (Sandbox Code Playgroud)

当我使用像log.info("message here"). 我尝试了INFO、WARN、ERROR级别- 没问题。但是,当我在控制器中收到RuntimeException时,我在日志中看到错误级别的堆栈跟踪,但没有提供 MDC 数据。

我应该如何在抛出异常时获取日志中的 MDC 数据?

Han*_*Lee 2

您可以catching先编写一个异常块MDC.clear()才能登录,doFilter如下所示。

        try {
            // Setup MDC data:
            String mdcData = String.format("[userId:%s | requestId:%s] ", "hello", "hello");
            MDC.put("mdcData", mdcData); //Variable 'mdcData' is referenced in Spring Boot's logging.pattern.level property
            chain.doFilter(request, response);
        } catch (Exception e) {
            log.error("", e);
        } finally {
           // Tear down MDC data:
           // ( Important! Cleans up the ThreadLocal data again )
            MDC.clear();
        }
Run Code Online (Sandbox Code Playgroud)

它将记录器从 DirectJDKLog 更改为 RequestFilter。

  • 可能想确保事后重新抛出异常 (2认同)