10

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.

Daniel Haughton
  • 1,085
  • 5
  • 20
  • 45

3 Answers3

12

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

}
mad_fox
  • 3,030
  • 5
  • 31
  • 43
9

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

}
Marcin Grzejszczak
  • 10,624
  • 1
  • 16
  • 32
4

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.

Yasammez
  • 1,383
  • 12
  • 15