简体   繁体   English

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

[英]Spring Boot not logs Mapped Diagnostic Context (MDC) on exception

I need to have Mapped Diagnostic Context data in logs. 我需要在日志中具有映射的诊断上下文数据。 Application build with: 应用程序构建具有:

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.8.RELEASE</version>
    <relativePath /> <!-- lookup parent from repository -->
</parent>

To get MDC in logs I put in application.properties file: 为了在日志中获取MDC,我将其放在application.properties文件中:

logging.pattern.level=%X{mdcData}%5p

and create a class 并创建一个类

@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();
        }
    }
...
}

The MDC data appears in logs when I use method call like log.info("message here") . 当我使用log.info("message here")类的方法调用时,MDC数据会出现在日志中。 I tried with levels INFO, WARN, ERROR - it is fine. 我尝试了INFO,WARN,ERROR级别-很好。 But when I get RuntimeException in my controller, I see the stack trace in logs with ERROR level, but no MDC data provided. 但是,当我在控制器中获得RuntimeException时,我在具有ERROR级别的日志中看到了堆栈跟踪,但未提供MDC数据。

What should I do to get MDC data in logs on exception thrown? 我应该怎么做才能在引发异常的日志中获取MDC数据?

You may write a block catching Exception before MDC.clear() in order to log in doFilter like below. 您可以在MDC.clear()之前编写一个catching Exception的块,以登录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();
        }

It changes logger from DirectJDKLog to RequestFilter. 它将记录器从DirectJDKLog更改为RequestFilter。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM