繁体   English   中英

在 spring 引导 3.0 中使用 @Scheduled 跟踪日志

[英]Tracing of logs with @Scheduled in spring boot 3.0

由于移动到 spring 引导 3.0 跟踪已停止使用计划作业@Scheduled(fixedDelay = 69, timeUnit = TimeUnit.SECONDS)

根据迁移文档,我们应该使用ContextScheduledExecutorService.wrap()包装执行程序服务https://github.com/micrometer-metrics/tracing/wiki/Spring-Cloud-Sleuth-3.1-Migration-Guide#async-instrumentation

根据 spring 文档,我们应该可以这样做

@Configuration
    @EnableScheduling
    public class AppConfig implements SchedulingConfigurer {

        @Override
        public void configureTasks(ScheduledTaskRegistrar taskRegistrar) {
            taskRegistrar.setScheduler(taskExecutor());
        }

        @Bean(destroyMethod="shutdown")
        public Executor taskExecutor() {
            return ContextScheduledExecutorService.wrap(Executors.newScheduledThreadPool(100));
        }
    }

https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/scheduling/annotation/EnableScheduling.html

正在使用正确的调度程序,因为我在设置调度程序时可以看到自定义线程名称,但日志跟踪未显示(traceId、spanId)。 否则跟踪工作就像我在同一应用程序中调用 api 方法时看到的那样。

我也遇到了同样的问题,并找到了一些对我有用的解决方案。 你可以这样做。

import io.micrometer.tracing.Tracer;
import lombok.RequiredArgsConstructor;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;

@Aspect
@Component
@RequiredArgsConstructor
public class ScheduledSpanAspect {
  private final Tracer tracer;

  @Pointcut("@annotation(org.springframework.scheduling.annotation.Scheduled)")
  public void annotatedWithScheduled() {}

  @Around("annotatedWithScheduled()")
  public Object wrapScheduledIntoSpan(ProceedingJoinPoint pjp) throws Throwable {
    var methodName = pjp.getSignature().getDeclaringTypeName() + "." + pjp.getSignature().getName();

    var span = tracer.nextSpan()
        .name(methodName)
        .start();
    try (var ignoredSpanInScope = tracer.withSpan(span.start())) {
      return pjp.proceed();
    } finally {
      span.end();
    }
  }
}

在这里找到

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM