sge
sge

Reputation: 718

Why is Tracer.getCurrentSpan() not working in spring cloud gateway after switching from sleuth to micrometer

Tracer.getCurrentSpan() does return null in my globalFilter on a spring cloud gateway service after i've switched from spring cloud sleuth to micrometer tracing. I'm using spring boot 3.1.x, micrometer-tracing 1.1.2 and micrometer-tracing-bridge-brave 1.1.2.

The global filter in my spring cloud gateway looks like this:

@Component
@RequiredArgsConstructor
public class GlobalFilterComponent implements GlobalFilter {

  private final Tracer tracer;

  @Override
  public Mono<Void> filter(final ServerWebExchange exchange, final GatewayFilterChain chain) {
    Optional<String> optionalTraceId = Optional.ofNullable(tracer)
                                               .map(Tracer::currentSpan)
                                               .map(Span::context)
                                               .map(TraceContext::traceIdString);

    return chain.filter(exchange.mutate().request(request).build()).then(Mono.fromRunnable(() -> {
      HttpHeaders responseHeader = exchange.getResponse().getHeaders();
      optionalTraceId.ifPresent(s -> responseHeader.add("trace-id", s));
    }));
  }
}

I configured the following settings in my application.yml

management:
  tracing:
    sampling:
      probability: 1.0
    propagation:
      type: b3

The sub services has the trace information in the request header (header -> b3: 6492a69fca49ba72a97fce4d01e21780-361f2e684d9fdc2d-1).

Any hints why Tracer.getCurrentSpan() does return null in the global filter?

Upvotes: 2

Views: 1384

Answers (1)

sge
sge

Reputation: 718

Solution is to add Hooks.enableAutomaticContextPropagation()

import reactor.core.publisher.Hooks;

@SpringBootApplication
public class MyApplication {

    public static void main(String[] args) {
        Hooks.enableAutomaticContextPropagation();

        SpringApplication.run(MyApplication.class, args);
    }

}

Upvotes: 4

Related Questions