SpringBoot应用如何实现Java日志追踪唯一ID?

SpringBoot应用Java日志追踪唯一ID实现指南

本文介绍如何在SpringBoot 2.3环境下为Java日志添加唯一的追踪ID,方便追踪每个请求的日志记录。 主要方法是结合拦截器和MDC(Mapped Diagnostic Context),利用日志框架的特性。

实现步骤:

1. 日志格式配置:

修改日志配置文件(例如logback-spring.xml),添加以下格式化标识符:

%x{request_id} 

这将使日志输出包含名为request_id的MDC变量的值。

2. 自定义拦截器:

创建一个拦截器,在请求处理前生成唯一的ID并将其存储到MDC中:

import org.slf4j.MDC;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;

public class LoggingInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestId = UUID.randomUUID().toString();
        MDC.put("request_id", requestId);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        // 可选:在此处添加其他处理逻辑
    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        MDC.remove("request_id");
    }
}

3. 拦截器注册:

在SpringBoot配置类中注册拦截器:

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class AppConfig implements WebMvcConfigurer {

  

@Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(new LoggingInterceptor()) .addPathPatterns("/**"); // 应用于所有路径 } }

4. 日志输出:

现在,在你的日志语句中,%x{request_id} 将会输出在拦截器中生成的唯一ID。

通过以上步骤,即可为每个请求生成唯一的日志追踪ID,方便排查问题和追踪请求流程。 请确保你的日志框架(例如Logback或Log4j2)已正确配置并支持MDC。