Spring Boot下为每条Java日志添加唯一ID实现追踪
本文介绍在Spring Boot 2.3和Java 1.8环境下,使用SLF4j日志框架为每条Java日志添加唯一ID以方便追踪的方法。 主要方案是结合拦截器、MDC和日志格式配置实现。
一、日志格式配置
修改logback.xml (或其他日志配置文件) ,在日志输出格式中添加%x{request_id}占位符:
立即学习“Java免费学习笔记(深入)”;
<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数据,避免内存泄漏 } }
四、其他建议
通过以上步骤,即可为每条日志添加唯一的请求ID,方便追踪和排查问题。
以上就是Spring Boot下如何为每条Java日志添加唯一ID方便追踪?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号