0

Similar to Spring Cloud Sleuth- Get current traceId? but in the context of Spring Cloud Gateway GlobalFilter

I tried to inject Tracing and get the currentTracingContext but it returns null when I get the current tracing context.

    @Autowired
    private Tracing tracing;

    @Override
    public Mono<Void> filter(final ServerWebExchange exchange, GatewayFilterChain chain) {

        final long startNanos = System.nanoTime();
        System.out.println(tracing.currentTraceContext().get()); // NULL
        return chain
            .filter(exchange)
            .then(
                Mono.fromRunnable(() -> {
                    System.out.println(tracing.currentTraceContext().get()); // NULL
                   ...

I am suspecting it is an order issue, my filter doesn't specify any @Order. However, I tried both HIGHEST_PRECEDENCE and LOWEST_PRECEDENCE, still returns null.

Archimedes Trajano
  • 35,625
  • 19
  • 175
  • 265

1 Answers1

0

You should call the WebFluxSpanOperators and retrieve the span from ServerWebExchange - https://github.com/spring-cloud/spring-cloud-sleuth/blob/v3.0.1/spring-cloud-sleuth-instrumentation/src/main/java/org/springframework/cloud/sleuth/instrument/web/WebFluxSleuthOperators.java#L166 . You should use other methods from that class to work with context propagation in the Gateway.

Marcin Grzejszczak
  • 10,624
  • 1
  • 16
  • 32
  • System.out.println(WebFluxSleuthOperators.currentTraceContext(exchange)); outputs `null` in the `then` method and inside the filter method itself. I confirmed my cloud sleuth is at 3.0.1. I recall seeing a bug regarding MDC + Spring Sleuth + Spring Cloud Gateway, but I couldnt' find it. – Archimedes Trajano Feb 22 '21 at 11:58
  • Hmm I don't think that at this line " System.out.println(tracing.currentTraceContext().get()); // NULL" you'll get the traceid unless you turn on the ON_EACH instrumentation mode that is highly discouraged. At thtat line in code nothing happens at runtime really. It's in the flux with the chain that processing is done and there you will have the trace context – Marcin Grzejszczak Feb 22 '21 at 12:09
  • Ok, but how does it write out the trace ID in the end (because there is a valid trace in zipkin)? That's the part I was trying to find in the code – Archimedes Trajano Feb 22 '21 at 12:21
  • Also per https://docs.spring.io/spring-cloud-sleuth/docs/current-SNAPSHOT/reference/html/integrations.html the default is ON_EACH. Which I also tried to set explicitly. – Archimedes Trajano Feb 22 '21 at 12:29
  • 1
    Not for the gateway. For Gateway it's MANUAL https://github.com/spring-cloud/spring-cloud-sleuth/issues/1710 – Marcin Grzejszczak Feb 22 '21 at 12:30
  • Good to know. I was about to set it to MANUAL as well and seee if I can get that example put in. However, I had it set ON_EACH and I was still not getting the value. – Archimedes Trajano Feb 22 '21 at 12:33