我需要在日志中包含映射的诊断上下文数据。应用程序构建:
<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数据?
答案 0 :(得分:0)
您可以在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();
}
它将记录器从DirectJDKLog更改为RequestFilter。