我需要在日志中映射诊断上下文数据。应用程序构建:
<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数据出现在日志中。我尝试使用级别信息,警告,错误 - 很好。但是,当我在控制器中获取 RuntimeException 时,我会在 error celver中看到堆栈跟踪,但没有提供MDC数据。
我该怎么做才能在例外的日志中获取MDC数据?
您可以在 MDC.clear()
之前写一个块 catching
异常,以便在下面登录 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更改为请求Filter。