在 Spring Boot 中的异常处理期间保留自定义 MDC 属性

and*_*ero 9 java error-handling spring mdc spring-boot

简短版本(有足够的细节)

如何保留在实现的doFilter()方法中添加的 MDC 属性javax.servlet.Filter...

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    try {
        MDC.put("token", MyToken.random()); // add the MDC attribute related to the current request processing
        chain.doFilter(request, response); // send the request to other filters and the Controller
    } finally {
        MDC.clear(); // MDC attribute must be removed so future tasks executed on the same thread would not log invalid information
    }
}
Run Code Online (Sandbox Code Playgroud)

... 在异常处理期间,如果异常发生在另一个过滤器或控制器中(对 的调用chain.doFilter(...))。

当前,如果发生异常:将执行 finally 块,清除 MDC,然后将异常抛出过滤器。异常处理期间的所有日志都不会包含 MDC 属性。

长版(过于详细)

我有一个简单的Filter实现来拦截所有请求。它只创建一个随机字符串(令牌)以包含在与处理请求相关的所有日志中。

@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class RequestFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) {
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        try {
            MDC.put("token", MyToken.random());
            chain.doFilter(request, response);
        } finally {
            MDC.clear();
        }
    }

    @Override
    public void destroy() {
    }
}
Run Code Online (Sandbox Code Playgroud)

事件的顺序是:

  1. 收到请求。
  2. MydoFilter()被调用,将随机令牌添加到 MDC。
  3. 请求是通过调用处理的chain.doFilter()
  4. 无论发生什么(处理完成,发生错误),MDC 都会清除finally块中的随机令牌。

问题在于,如果发生错误并对其进行处理(例如通过自定义ErrorController实现),相关日志不包含令牌:

[2019.03.13 15:00:14.535] token:308...8bf [DEBUG] 8124 [https-jsse-nio-8443-exec-7] o.s.w.s.DispatcherServlet                  : GET "/resource", parameters={}
[2019.03.13 15:00:14.551] token:308...8bf [DEBUG] 8124 [https-jsse-nio-8443-exec-7] o.s.w.s.DispatcherServlet                  : Completed 400 BAD_REQUEST
[2019.03.13 15:00:14.551] token:          [DEBUG] 8124 [https-jsse-nio-8443-exec-7] o.s.w.s.DispatcherServlet                  : "ERROR" dispatch for GET "/error", parameters={}
[2019.03.13 15:00:14.551] token:          [DEBUG] 8124 [https-jsse-nio-8443-exec-7] o.s.w.s.m.m.a.RequestMappingHandlerMapping : Mapped to public org.springframework.http.ResponseEntity myproj.CustomErrorController.handleError(javax.servlet.http.HttpServletRequest)
[2019.03.13 15:00:14.551] token:          [ERROR] 8124 [https-jsse-nio-8443-exec-7] m.CustomErrorController                    : HTTP Error: Bad Request (400)
[2019.03.13 15:00:14.551] token:          [DEBUG] 8124 [https-jsse-nio-8443-exec-7] o.s.w.s.DispatcherServlet                  : Exiting from "ERROR" dispatch, status 400
Run Code Online (Sandbox Code Playgroud)

finallyController处理它的程序抛出异常时执行该块,从而清除 MDC。

ErrorController在此之后执行错误处理(包括 custom ),这意味着相关日志中没有更多令牌。

如何将自定义令牌添加到与从接收请求到发送响应的整个请求处理相关的所有日志中,包括错误处理?我希望在线程发送响应后清除 MDC,作为最后一个操作。无论发生什么(成功响应、错误处理期间抛出的异常等),都应该清除 MDC。

由于多个客户端同时使用 Rest 服务,日志可能会变得非常混乱。在某个请求的整个处理过程中产生的每个日志上附加一个唯一的令牌将大大简化调试。

Pin*_*ino -1

标准servlet 过滤器在任何 servlet周围执行,包括 Spring 的(例如,参见此处),但您的过滤器是 Spring 组件。由于它不使用任何 Spring bean,您可以轻松地将其转换为普通过滤器,这是在我链接的页面中描述的配置过滤器。DispatcherServletweb.xml