
Spring Boot应用日志追踪:实现唯一ID
本文探讨如何在Spring Boot 2.3应用中为每条日志记录分配唯一标识符,方便追踪特定请求的日志信息。我们将介绍两种方案:基于拦截器的自动分配和基于MDC的手动设置。
方案一:使用拦截器自动分配唯一ID
此方案通过实现HandlerInterceptor,在请求处理前使用UUID生成唯一ID并存储于MDC(Mapped Diagnostic Context)。请求结束后清除MDC,避免干扰后续请求。
1. 拦截器注册:
在Spring配置中注册拦截器,拦截所有请求,并排除静态资源:
<code class="java">@Configuration
public class MvcConfigurer implements WebMvcConfigurer {
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(new TraceInterceptor());
}
}
public class TraceInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
MDC.put("tid", UUID.randomUUID().toString());
return true;
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
MDC.remove("tid");
}
}</code>2. 日志配置:
在logback-spring.xml (或其他日志配置文件) 中,添加自定义PatternLayout,包含%X{tid}占位符:
<code class="xml"><configuration>
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%-5level] [%thread] %X{tid} %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<root level="info">
<appender-ref ref="CONSOLE"/>
</root>
</configuration></code>方案二:直接使用MDC手动设置唯一ID
此方案无需额外拦截器或配置修改,但需要在每个日志记录处手动设置ID。
示例:
<code class="java">public class MyService {
public void myMethod() {
String tid = UUID.randomUUID().toString();
MDC.put("tid", tid);
log.info("This is a log message."); // tid will be included in this log message
MDC.remove("tid");
}
}</code>方案对比:
选择哪种方案取决于项目需求和编码风格偏好。 对于大型项目,推荐使用方案一,以保证一致性和减少出错可能性。
以上就是Spring Boot应用如何实现日志追踪的唯一ID?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号