简体   繁体   中英

Tracing of logs with @Scheduled in spring boot 3.0

Since moving to spring boot 3.0 tracing has stopped working with scheduled jobs @Scheduled(fixedDelay = 69, timeUnit = TimeUnit.SECONDS)

According to migration docs we should be wrapping the executor service with ContextScheduledExecutorService.wrap() https://github.com/micrometer-metrics/tracing/wiki/Spring-Cloud-Sleuth-3.1-Migration-Guide#async-instrumentation

And according to spring docs we should be able to do it like this

@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

The correct scheduler is being used as I can see custom thread name when setting one, but log tracing does not show up (traceId, spanId). Otherwise tracing works as I can see it when calling api methods in same application.

I also faced the same issue and found some solution which worked for me. You can do something like this.

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();
    }
  }
}

Found it here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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