Search code examples
spring-bootspring-cloud-sleuth

Spring Cloud Sleuth- Get current traceId?


I am using Sleuth and I am wondering is it possible to get the current traceId? I dont need to add it any responses or anything. I just want the traceId for emails alerting the development team in certain situations.


Solution

  • Inject the Tracer bean and call tracer.currentSpan() to get the current span. From there you can get the trace id.

    Please use Sleuth's API - that way regardless of which Tracer library you're using (Brave / OTel) your code will remain the same.

    Example:

    import org.springframework.cloud.sleuth.Span;
    import org.springframework.cloud.sleuth.Tracer;
    
    @Component
    public class TraceService {
    
        private final Tracer tracer;
    
        public TraceService(Tracer tracer) {
            this.tracer = tracer;
        }
    
        public String traceId() {
            Span span = tracer.currentSpan();
            String traceId = span.context().traceId();
            System.out.println(traceId);
            return traceId;
        }
    
    }