gpt4 book ai didi

spring-boot - Spring Boot 不会在异常时记录映射诊断上下文 (MDC)

转载 作者:行者123 更新时间:2023-12-04 14:00:41 25 4
gpt4 key购买 nike

我需要在日志中有映射的诊断上下文数据。应用程序构建:

<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 数据出现在日志中.我尝试了级别 信息、警告、错误 - 没事。但是当我得到 运行时异常 在我的 Controller 中,我看到日志中的堆栈跟踪 错误 级别,但未提供 MDC 数据。

我应该怎么做才能在抛出异常的日志中获取 MDC 数据?

最佳答案

你可以写一个块 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。

关于spring-boot - Spring Boot 不会在异常时记录映射诊断上下文 (MDC),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47835271/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com