Spring Boot下为每条Java日志添加唯一ID实现追踪
本文介绍在Spring Boot 2.3和Java 1.8环境下,使用SLF4j日志框架为每条Java日志添加唯一ID以方便追踪的方法。 主要方案是结合拦截器、MDC和日志格式配置实现。
一、日志格式配置
修改logback.xml (或其他日志配置文件) ,在日志输出格式中添加%x{request_id}占位符:
<pattern>%d{${log_dateformat_pattern:yyyy-mm-dd HH:mm:ss.SSS}} ${log_level_pattern:%5p} ${pid: } --- [%t] %-40.40logger{39} :%x{request_id} %m%n${log_exception_conversion_word:%wex}</pattern>
二、创建HTTP请求拦截器
实现Spring Boot的WebMvcConfigurer接口:
@Configuration public class MvcLoggingConfigurer implements WebMvcConfigurer { @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new LoggingHandlerInterceptor()); } }
三、自定义拦截器LoggingHandlerInterceptor
在preHandle方法中生成唯一ID并使用MDC存储:
public class LoggingHandlerInterceptor implements HandlerInterceptor { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) { String requestId = UUID.randomUUID().toString(); // 生成唯一ID MDC.put("REQUEST_ID", requestId); // 使用MDC存储唯一ID return true; } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { MDC.remove("REQUEST_ID"); // 清除MDC数据,避免内存泄漏 } }
四、其他建议
- 可以根据需要在MDC中存储其他上下文信息,例如用户ID、会话ID等,以便更全面地追踪日志。
- 务必在afterCompletion方法中移除MDC中的REQUEST_ID,防止内存泄漏。
- 考虑使用Log4j 2.x作为日志框架,它提供了更强大的功能和性能。
通过以上步骤,即可为每条日志添加唯一的请求ID,方便追踪和排查问题。