[英]Preserve custom MDC attributes during exception-handling in Spring Boot
[英]Spring Boot not logs Mapped Diagnostic Context (MDC) on exception
我需要在日志中具有映射的诊断上下文数据。 应用程序构建具有:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.5.8.RELEASE</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
为了在日志中获取MDC,我将其放在application.properties文件中:
logging.pattern.level=%X{mdcData}%5p
并创建一个类
@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("message here")
类的方法调用时,MDC数据会出现在日志中。 我尝试了INFO,WARN,ERROR级别-很好。 但是,当我在控制器中获得RuntimeException时,我在具有ERROR级别的日志中看到了堆栈跟踪,但未提供MDC数据。
我应该怎么做才能在引发异常的日志中获取MDC数据?
您可以在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();
}
它将记录器从DirectJDKLog更改为RequestFilter。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.