Spring boot Spring引导未记录异常时的映射诊断上下文(MDC)
我需要在日志中映射诊断上下文数据。应用程序构建包括:Spring boot Spring引导未记录异常时的映射诊断上下文(MDC),spring-boot,logging,mdc,Spring Boot,Logging,Mdc,我需要在日志中映射诊断上下文数据。应用程序构建包括: <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>1.5.8.RELEASE</version> <relativePath /> <
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.8.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
并创建一个类
@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();
}
}
...
}
当我使用类似于log.info(“messagehere”)
的方法调用时,MDC数据出现在日志中。我尝试了级别信息、警告、错误-没问题。但是,当我在控制器中获得RuntimeException时,我会在日志中看到ERROR级别的堆栈跟踪,但没有提供MDC数据
在抛出异常时,如何在日志中获取MDC数据?您可以在
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();
}
它将记录器从DirectJDKLog更改为RequestFilter。我也面临同样的问题。你能找到原因吗?我也遇到了这个问题。我认为问题在于,在finally块清除MDC之后,Spring将异常记录在日志过滤器之外。我还不确定如何解决这个问题。我确认,如果我从finally块中删除MDC.clear(),数据将显示在记录的异常中。我认为这是安全的,因为Jetty使用一个专用的线程池来处理请求,所以在完成任何工作之前,MDC总是会被过滤器重置。但对此不是100%确定。@karlgold您是否能够确认这是否是获得异常MDC数据的正确方法?
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();
}