Daniel Haughton
Daniel Haughton

Reputation: 1215

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.

Upvotes: 11

Views: 13933

Answers (3)

Marcin Grzejszczak
Marcin Grzejszczak

Reputation: 11149

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

}

Upvotes: 9

Yasammez
Yasammez

Reputation: 1551

If there is no current trace in progress, tracer.currentSpan() will return null and hence tracer.currentSpan().context() will throw a NPE. If you are unsure if there is a current trace and want to create one if none does exist, you should use

var span = tracer.startScopedSpan("fancyTitle");
try {
    var traceId = span.context().traceIdString();
    // use traceId ...
} finally {
    span.finish(); // clean up after yourself
}

Note that this will create a new span in an existing trace, i.e. always generate a new spanId.

Upvotes: 4

mad_fox
mad_fox

Reputation: 3188

Ex

import brave.Span;
import brave.Tracer;

@Service
public class TraceService {

    Tracer tracer;

    public TraceService(Tracer tracer) {
        this.tracer = tracer;
    }

    public void printTraceId() {
        Span span = tracer.currentSpan();
        String traceId = span.context().traceIdString();
        System.out.println(traceId);
    }

}

Upvotes: 12

Related Questions