Skip to content

Instantly share code, notes, and snippets.

@Ananto30
Created January 28, 2020 15:25
Show Gist options
  • Save Ananto30/6789842bb604019b701784a8ceaf9fb2 to your computer and use it in GitHub Desktop.
Save Ananto30/6789842bb604019b701784a8ceaf9fb2 to your computer and use it in GitHub Desktop.
@Component
@Slf4j
public class TraceIdFilter implements WebFilter {
@Override
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) {
Map<String, String> headers = exchange.getRequest().getHeaders().toSingleValueMap();
return chain.filter(exchange)
.subscriberContext(context -> {
var traceId = "";
if (headers.containsKey("X-B3-TRACEID")) {
traceId = headers.get("X-B3-TRACEID");
MDC.put("X-B3-TraceId", traceId);
} else if (!exchange.getRequest().getURI().getPath().contains("/actuator")) {
log.warn("TRACE_ID not present in header: {}", exchange.getRequest().getURI());
}
// simple hack to provide the context with the exchange, so the whole chain can get the same trace id
Context contextTmp = context.put("X-B3-TraceId", traceId);
exchange.getAttributes().put("X-B3-TraceId", traceId);
return contextTmp;
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment