嗨,你好啊,我是猿java
在分布式系统或微服务架构中,全链路追踪(Full-Chain Tracing) 对诊断和监控系统的性能至关重要。这篇文章,我们将详细介绍如何使用 SLF4J 的 MDC 实现全链路的 traceId。
1. 什么是 SLF4J 的MDC?
MDC(Mapped Diagnostic Context,映射诊断上下文)是 SLF4J 提供的一种上下文机制,它允许在日志记录时附加一些关键的上下文信息(如 traceId、userId 等),这些信息可以在日志格式中被引用,从而丰富日志内容,便于后续的日志分析和追踪。
2. 如何实现全链路 traceId?
2.1 生成或提取 traceId
在请求的入口点,通常来说是客户端(比如浏览器、移动应用等,也可以是 Web 控制器、服务网关等)生成一个唯一的 traceId,
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
   | import org.slf4j.MDC; import java.util.UUID;
  public void handleRequest(HttpServletRequest request) {     String traceId = request.getHeader("X-Trace-Id");     if (traceId == null || traceId.isEmpty()) {         traceId = UUID.randomUUID().toString();     }     MDC.put("traceId", traceId);     try {              } finally {         MDC.remove("traceId");      } }
   | 
 
2.2 配置日志格式以包含 traceId
在日志配置文件(如 logback.xml 或 log4j2.xml)中,将 traceId 添加到日志输出格式中。例如,使用 Logback 时:
1 2 3 4 5 6 7 8 9 10
   | <configuration>     <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">         <encoder>             <pattern>[%d{yyyy-MM-dd HH:mm:ss}] [traceId:%X{traceId}] %-5level %logger{36} - %msg%n</pattern>         </encoder>     </appender>     <root level="info">         <appender-ref ref="STDOUT" />     </root> </configuration>
   | 
 
这样,每条日志都会包含 traceId,便于后续追踪。
2.3 传播 traceId 到下游服务
当一个服务调用下游服务时,需要确保 traceId 被传递。通常通过 HTTP 头部传递,例如使用X-Trace-Id或者tracestate 头:
1 2 3 4 5 6 7 8 9 10 11 12 13
   | import org.springframework.web.client.RestTemplate; import org.springframework.http.HttpHeaders; import org.springframework.http.HttpEntity;
  public void callDownstreamService() {     String traceId = MDC.get("traceId");     HttpHeaders headers = new HttpHeaders();     headers.set("X-Trace-Id", traceId);     HttpEntity<String> entity = new HttpEntity<>(headers);          RestTemplate restTemplate = new RestTemplate();     restTemplate.exchange("http://downstream-service/api", HttpMethod.GET, entity, String.class); }
   | 
 
2.4 在下游服务中设置 traceId 到 MDC
下游服务在接收到请求时,需要从请求头中提取 traceId 并设置到 MDC:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
   | public void handleDownstreamRequest(HttpServletRequest request) {     String traceId = request.getHeader("X-Trace-Id");     if (traceId != null && !traceId.isEmpty()) {         MDC.put("traceId", traceId);     } else {         traceId = UUID.randomUUID().toString();         MDC.put("traceId", traceId);     }     try {              } finally {         MDC.remove("traceId");     } }
  | 
 
2.5 处理多线程环境下的 traceId 传播
在多线程环境中,如使用线程池或异步任务,MDC 的上下文默认不会自动传播到子线程。需要手动传递 traceId:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
   | import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors;
  public void executeAsyncTask() {     String traceId = MDC.get("traceId");     ExecutorService executor = Executors.newFixedThreadPool(10);     executor.submit(() -> {         MDC.put("traceId", traceId);         try {                      } finally {             MDC.remove("traceId");         }     }); }
   | 
 
为了简化多线程环境下的 MDC 传播,可以使用像 MDC Decorator 或自定义 Executor 来自动管理 MDC。
3. 使用拦截器或过滤器统一管理 traceId
为了避免在每个请求处理方法中手动设置和清理 traceId,可以使用 Spring 的拦截器(Interceptor)或 Servlet 过滤器(Filter)来统一管理:
示例:使用 Spring 的 OncePerRequestFilter
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
   | import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.slf4j.MDC; import org.springframework.web.filter.OncePerRequestFilter;
  public class TraceIdFilter extends OncePerRequestFilter {     @Override     protected void doFilterInternal(HttpServletRequest request,                                     HttpServletResponse response,                                     FilterChain filterChain)             throws ServletException, IOException {         String traceId = request.getHeader("X-Trace-Id");         if (traceId == null || traceId.isEmpty()) {             traceId = UUID.randomUUID().toString();         }         MDC.put("traceId", traceId);         try {             filterChain.doFilter(request, response);         } finally {             MDC.remove("traceId");         }     } }
   | 
 
将该过滤器注册到 Spring 容器中即可。
4. 示例代码
1. 过滤器类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
   | import javax.servlet.FilterChain; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.slf4j.MDC; import org.springframework.web.filter.OncePerRequestFilter; import java.io.IOException; import java.util.UUID;
  public class TraceIdFilter extends OncePerRequestFilter {     private static final String TRACE_ID_HEADER = "X-Trace-Id";
      @Override     protected void doFilterInternal(HttpServletRequest request,                                     HttpServletResponse response,                                     FilterChain filterChain)             throws ServletException, IOException {         String traceId = request.getHeader(TRACE_ID_HEADER);         if (traceId == null || traceId.isEmpty()) {             traceId = UUID.randomUUID().toString();         }         MDC.put("traceId", traceId);         try {             filterChain.doFilter(request, response);         } finally {             MDC.remove("traceId");         }     } }
   | 
 
2. Spring Boot 中注册过滤器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
   | import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.boot.web.servlet.FilterRegistrationBean;
  @Configuration public class WebConfig {     @Bean     public FilterRegistrationBean<TraceIdFilter> traceIdFilter() {         FilterRegistrationBean<TraceIdFilter> registrationBean = new FilterRegistrationBean<>();         registrationBean.setFilter(new TraceIdFilter());         registrationBean.addUrlPatterns("/*");          registrationBean.setOrder(1);          return registrationBean;     } }
   | 
 
3. 日志配置(logback.xml)
1 2 3 4 5 6 7 8 9 10
   | <configuration>     <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">         <encoder>             <pattern>[%d{yyyy-MM-dd HH:mm:ss}] [traceId:%X{traceId}] %-5level %logger{36} - %msg%n</pattern>         </encoder>     </appender>     <root level="info">         <appender-ref ref="STDOUT" />     </root> </configuration>
   | 
 
5. 注意事项
在使用一项技术或者一个框架时,我们都需要知道有什么弊端,这样才能更好的帮助我们做好技术决策,下面是使用MDC需要注意的事项:
- 线程安全:在多线程环境下,确保 
MDC 的设置和清理,以避免 traceId 泄漏到其他线程。 
- 性能影响:频繁操作 
MDC 可能略微影响性能,需权衡日志详细程度和性能需求。 
- 日志存储:确保日志存储系统支持和索引 
traceId,以便高效查询和分析。 
- 异常处理:在异常情况下,确保 
traceId 仍能正确记录在日志中,有助于快速定位问题。 
6. 总结
本文,我们分析了如何使用MDC实现全链路追踪,通过合理使用 SLF4J的MDC,可以在分布式系统中实现全链路的 traceId 追踪,提升日志的可读性和追踪能力。但是,对于更复杂的需求,我们还是建议结合专门的分布式追踪工具,比如 Spring Cloud Sleuth、Zipkin 或 Jaeger,以获得更全面的追踪能力。
7. 学习交流
如果你觉得文章有帮助,请帮忙转发给更多的好友,或关注公众号:猿java,持续输出硬核文章。