You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Spring Boot 3.0中@Scheduled任务日志追踪失效问题排查

解决Spring Boot 3 @Scheduled定时任务日志追踪失效问题

针对Spring Boot 3迁移后@Scheduled定时任务不显示traceId/spanId的问题,结合你的配置情况,给出以下排查和修复方案:

  • 修正自定义调度器的Bean类型
    当前配置中返回的Executor类型无法完全适配ScheduledTaskRegistrar的需求,ContextScheduledExecutorService本身实现了ScheduledExecutorService,修改配置类的返回类型:

    @Configuration
    @EnableScheduling
    public class AppConfig implements SchedulingConfigurer {
    
        @Override
        public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
            taskRegistrar.setScheduler(taskScheduler());
        }
    
        @Bean(destroyMethod = "shutdown")
        public ScheduledExecutorService taskScheduler() {
            return ContextScheduledExecutorService.wrap(Executors.newScheduledThreadPool(100));
        }
    }
    

    类型匹配后,上下文传递的包装逻辑才能完全生效。

  • 确认依赖配置正确性
    Spring Boot 3后,链路追踪依赖从Spring Cloud Sleuth切换为Micrometer Tracing,确保项目中引入了正确的依赖:
    Maven示例:

    <dependency>
        <groupId>io.micrometer</groupId>
        <artifactId>micrometer-tracing-bridge-brave</artifactId>
    </dependency>
    <dependency>
        <groupId>io.zipkin.reporter2</groupId>
        <artifactId>zipkin-reporter-brave</artifactId>
    </dependency>
    

    Gradle示例:

    implementation 'io.micrometer:micrometer-tracing-bridge-brave'
    implementation 'io.zipkin.reporter2:zipkin-reporter-brave'
    
  • 检查日志格式配置
    确保日志输出格式中包含traceId和spanId的占位符,比如在application.yml中配置:

    logging:
      pattern:
        console: "%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level [%X{traceId:-},%X{spanId:-}] %logger{36} - %msg%n"
    

    或者logback配置文件中添加对应的占位符。

  • 手动初始化Span(兜底方案)
    定时任务没有API请求那样的入口Span触发,若上述方案无效,可在任务方法内手动创建Span:

    @Autowired
    private Tracer tracer;
    
    @Scheduled(fixedDelay = 69, timeUnit = TimeUnit.SECONDS)
    public void scheduledTask() {
        try (Tracer.SpanInScope spanInScope = tracer.startScopedSpan("your-task-name")) {
            // 任务业务逻辑
            log.info("定时任务执行");
        }
    }
    

    手动创建的Span会自动将traceId/spanId注入到MDC上下文,日志就能正常显示。

内容的提问来源于stack exchange,提问作者ieatlettuce

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.06 01:45:42