跳到主要内容

日志链路追踪

SpringBoot日志链路追踪

使用步骤

导入依赖:

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</dependency>

配置resources/logback-spring.xml:

<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="false">
<!--日志存储路径-->
<property name="log" value="./logs" />
<!-- 控制台输出 -->
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<!--输出格式化-->
<pattern>[%X{TRACE_ID}] %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
</encoder>
</appender>
<!-- 按天生成日志文件 -->
<appender name="file" class="ch.qos.logback.core.rolling.RollingFileAppender">
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!--日志文件名-->
<FileNamePattern>${log}/%d{yyyy-MM-dd}.log</FileNamePattern>
<!--保留天数-->
<MaxHistory>30</MaxHistory>
</rollingPolicy>
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<pattern>[%X{TRACE_ID}] %d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
</encoder>
<!--日志文件最大的大小-->
<triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
<MaxFileSize>10MB</MaxFileSize>
</triggeringPolicy>
</appender>

<!-- 日志输出级别 -->
<root level="INFO">
<appender-ref ref="console" />
<appender-ref ref="file" />
</root>
</configuration>

在application.yml中指定日志配置的路径:

logging:
config: classpath:logback-spring.xml

编写日志拦截器:

public class LogInterceptor implements HandlerInterceptor {

private static final String TRACE_ID = "TRACE_ID";

@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
String tid = UUID.randomUUID().toString().replace("-", "");
// 可以考虑让客户端传入链路ID,但需保证一定的复杂度唯一性;如果没使用默认UUID自动生成
if (!StringUtils.isEmpty(request.getHeader("TRACE_ID"))) {
tid = request.getHeader("TRACE_ID");
}
MDC.put(TRACE_ID, tid);
return true;
}

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

配置拦截器:

@Configuration
public class WebConfigurerAdapter implements WebMvcConfigurer {
@Bean
public LogInterceptor logInterceptor() {
return new LogInterceptor();
}

@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(logInterceptor()).addPathPatterns("/**");
//可以具体制定哪些需要拦截,哪些不拦截,其实也可以使用自定义注解更灵活完成
// .excludePathPatterns("/testxx.html");
}
}

测试:

@ResponseBody
@GetMapping(value = "/pay/{orderSn}")
public String alipay(@PathVariable("orderSn") String orderSn) {
log.info("我开始了!");
String result = orderService.alipay(orderSn);
log.info("我结束了!{}",result);
return result;
}

@Override
public String alipay(String orderSn) {
try {
log.info("开始查询");
Thread.sleep(1000);
int i = 10 / 0;
} catch (Exception e) {
log.error("有个错误:{}", e.getMessage());
}
log.info("查询结束");
return "haha";
}

效果:

image-20240910155544689

异步问题

如果是异步,会找不到id

image-20240910155810887

解决办法:

将父线程的trace ID传递给子线程

包装类:

对Task进行装饰,将父线程的traceID放到子线程中

public final class MyThreadPoolTaskExecutor extends ThreadPoolTaskExecutor {
public MyThreadPoolTaskExecutor() {
super();
}

@Override
public void execute(Runnable task) {
super.execute(ThreadMdcUtil.wrap(task, MDC.getCopyOfContextMap()));
}
@Override
public <T> Future<T> submit(Callable<T> task) {
return super.submit(ThreadMdcUtil.wrap(task, MDC.getCopyOfContextMap()));
}

@Override
public Future<?> submit(Runnable task) {
return super.submit(ThreadMdcUtil.wrap(task, MDC.getCopyOfContextMap()));
}
}

配置线程池,传递刚刚写的装饰器:

@Configuration
@EnableAsync
public class ThreadPoolConfig {
@Bean("MyExecutor")
public Executor asyncExecutor() {
MyThreadPoolTaskExecutor executor = new MyThreadPoolTaskExecutor();
//核心线程数5:线程池创建时候初始化的线程数
executor.setCorePoolSize(5);
//最大线程数5:线程池最大的线程数,只有在缓冲队列满了之后才会申请超过核心线程数的线程
executor.setMaxPoolSize(5);
//缓冲队列500:用来缓冲执行任务的队列
executor.setQueueCapacity(500);
//允许线程的空闲时间60秒:当超过了核心线程出之外的线程在空闲时间到达之后会被销毁
executor.setKeepAliveSeconds(60);
//线程池名的前缀:设置好了之后可以方便我们定位处理任务所在的线程池
executor.setThreadNamePrefix("asyncJCccc");
executor.initialize();
return executor;
}
}

工具类:

public final class ThreadMdcUtil {
private static final String TRACE_ID = "TRACE_ID";

// 获取唯一性标识
public static String generateTraceId() {
return UUID.randomUUID().toString();
}

public static void setTraceIdIfAbsent() {
if (MDC.get(TRACE_ID) == null) {
MDC.put(TRACE_ID, generateTraceId());
}
}

/**
* 用于父线程向线程池中提交任务时,将自身MDC中的数据复制给子线程
*/
public static <T> Callable<T> wrap(final Callable<T> callable, final Map<String, String> context) {
return () -> {
if (context == null) {
MDC.clear();
} else {
MDC.setContextMap(context);
}
setTraceIdIfAbsent();
try {
return callable.call();
} finally {
MDC.clear();
}
};
}

/**
* 用于父线程向线程池中提交任务时,将自身MDC中的数据复制给子线程
*/
public static Runnable wrap(final Runnable runnable, final Map<String, String> context) {
return () -> {
if (context == null) {
MDC.clear();
} else {
MDC.setContextMap(context);
}
setTraceIdIfAbsent();
try {
runnable.run();
} finally {
MDC.clear();
}
};
}
}

分布式链路追踪

todo