[英]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.