Last active
January 10, 2023 02:18
-
-
Save jei0486/a8a2b842f15456124bac712fd20bbec7 to your computer and use it in GitHub Desktop.
MDC with webflux
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Slf4j | |
@Configuration | |
public class MdcLoggingFilter implements WebFilter { | |
private static final String MDC_KEY_TRACE_ID = "traceId"; | |
@Override | |
public Mono<Void> filter(ServerWebExchange exchange, WebFilterChain chain) { | |
ServerHttpRequest request = exchange.getRequest(); | |
String requestId = getRequestId(request.getHeaders()); | |
return chain | |
.filter(exchange) | |
.doOnEach(logOnEach(r -> log.info("{} {}", request.getMethod(), request.getURI()))) | |
.contextWrite(Context.of("CONTEXT_KEY", requestId)); | |
} | |
private String getRequestId(HttpHeaders headers) { | |
List<String> requestIdHeaders = headers.get("X-Request-ID"); | |
return requestIdHeaders == null || requestIdHeaders.isEmpty() | |
? UUID.randomUUID().toString() | |
: requestIdHeaders.get(0); | |
} | |
public static <T> Consumer<Signal<T>> logOnEach(Consumer<T> logStatement) { | |
return signal -> { | |
String contextValue = signal.getContextView().get("CONTEXT_KEY"); | |
try (MDC.MDCCloseable cMdc = MDC.putCloseable(MDC_KEY_TRACE_ID, contextValue)) { | |
logStatement.accept(signal.get()); | |
} | |
}; | |
} | |
public static <T> Consumer<Signal<T>> logOnNext(Consumer<T> logStatement) { | |
return signal -> { | |
if (!signal.isOnNext()) return; | |
String contextValue = signal.getContextView().get("CONTEXT_KEY"); | |
try (MDC.MDCCloseable cMdc = MDC.putCloseable(MDC_KEY_TRACE_ID, contextValue)) { | |
logStatement.accept(signal.get()); | |
} | |
}; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment