Skip to content

Accessing trace ID within reactive WebFilter #30470

Closed as not planned
Closed as not planned
@chechoochoo

Description

@chechoochoo

Affects: 6.0.8 (spring-webflux)


I have a simple filter that should just inject current trace ID to the response:

package some.controller;

import io.micrometer.tracing.Span;
import io.micrometer.tracing.Tracer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

import java.util.UUID;

@Slf4j
@Component
public class AddResponseHeaderWebFilter implements WebFilter, Ordered {

    private final Tracer tracer;

    public AddResponseHeaderWebFilter(
        final Tracer tracer
    ) {
        this.tracer = tracer;
    }

    @SuppressWarnings("NullableProblems")
    @Override
    public Mono<Void> filter(final ServerWebExchange exchange, final WebFilterChain chain) {
        return chain.filter(withCallback(exchange));
    }

    private ServerWebExchange withCallback(final ServerWebExchange exchange) {
        exchange
            .getResponse()
            .beforeCommit(() -> {
                HttpHeaders httpHeaders = exchange.getResponse().getHeaders();

                httpHeaders.add("trace-id", callId());

                return Mono.empty();
            });

        return exchange;
    }

    private static String fallbackValue() {
        String fallbackValue = UUID.randomUUID().toString();
        log.warn("Could not use trace ID; generated dummy UUID for tracking purposes: {}", fallbackValue);

        return fallbackValue;
    }

    private String callId() {
        Span currentSpan = this.tracer.currentSpan();

        return currentSpan == null
            ? fallbackValue()
            : currentSpan.context().traceId();
    }

    @Override
    public int getOrder() {
        return Ordered.HIGHEST_PRECEDENCE;
    }
}

it works well if my controller returns Mono<List> or Mono but always falls into "fallback" when controller returns Flux;

I am not sure if it is a known limitation now, or some additional configuration / code change is needed on my end?

Metadata

Metadata

Assignees

Labels

in: webIssues in web modules (web, webmvc, webflux, websocket)status: invalidAn issue that we don't feel is validtheme: observabilityAn issue related to observability and tracing

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions