Spring Cloud Sleuth- Get current traceId?
Asked Answered
S

3

11

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.

Stationery answered 9/8, 2019 at 9:26 Comment(0)
Y
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;
    }

}
Yesseniayester answered 9/8, 2019 at 9:48 Comment(0)
W
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);
    }

}
Wash answered 20/12, 2019 at 14:38 Comment(0)
Y
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;
    }

}
Yesseniayester answered 9/8, 2019 at 9:48 Comment(0)
A
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.

Alys answered 14/4, 2021 at 7:2 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.