Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add reactive application with database and Kafka #146

Open
mfvanek opened this issue Aug 1, 2024 · 0 comments
Open

Add reactive application with database and Kafka #146

mfvanek opened this issue Aug 1, 2024 · 0 comments

Comments

@mfvanek
Copy link
Owner

mfvanek commented Aug 1, 2024

import io.micrometer.tracing.handler.TracingObservationHandler.TracingContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.server.reactive.observation.ServerRequestObservationContext;
import org.springframework.web.server.ServerWebExchange;
import org.springframework.web.server.WebFilter;
import org.springframework.web.server.WebFilterChain;
import reactor.core.publisher.Mono;

public class TraceIdInResponseReactiveFilter implements WebFilter {

    private static final Logger logger = LoggerFactory.getLogger(TraceIdInResponseReactiveFilter.class);

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
        exchange.getResponse().beforeCommit(() -> {
            final ServerRequestObservationContext observationContext = exchange.getAttribute(ServerRequestObservationContext.CURRENT_OBSERVATION_CONTEXT_ATTRIBUTE);
            if (observationContext != null) {
                final TracingContext traceContext = observationContext.get(TracingContext.class);
                if (traceContext != null) {
                    final String traceId = traceContext.getSpan().context().traceId();
                    exchange.getResponse().getHeaders().add("X-Trace-Id", traceId);
                    logger.debug("Added TraceId: {} to the response", traceId);
                }
            }
            return Mono.empty();
        });
        return chain.filter(exchange);
    }
}
spring:
  reactor:
    context-propagation: auto # Important!!!
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant