1

I have MDC context and it is using for logging. I`m starting reactive chain from Scheduler and generating context:

private void generateMDCcontext() {
        UUID uuid = UUID.randomUUID();
        MDC.put("requestid", uuid.toString());
}

Next, I have WebClient for external http request and during request I lost my context. This is initialization WebClient in constructor:

this.webClient = WebClient.create().mutate()
                .clientConnector(new JettyClientHttpConnector(httpClient))
                .build();

And below I`m sending request:

log.info("Before request");
return webClient.post()
                .uri(addr)
                .acceptCharset(StandardCharsets.UTF_8)
                .contentLength(BODY_LENGTH)
                .retrieve()
                .onStatus(HttpStatus::isError, response -> Mono.error(...)//custom error
                .bodyToMono(CustomResponse.class)
                .timeout(timeuot)
                .doOnError(e -> log.error("Error during request ");
                )
                .onErrorMap(e -> {
                return customExceptoin;
                })
                .doOnSuccess(resp -> {
                log.info("Success, response: {}", resp == null ? null : resp);
                });
    }

If I have problem with external server, I`m waiting next result:

2022-07-28 15:01:20.128 requestid[7fa703d7-5d99-4502-b3cf-0e4737a2d7be] INFO Before request
2022-07-28 15:01:20.228 requestid[7fa703d7-5d99-4502-b3cf-0e4737a2d7be] ERROR Error during request
2022-07-28 15:01:20.328 requestid[7fa703d7-5d99-4502-b3cf-0e4737a2d7be] ERROR CustomExceptiomMsg

But I`m getting logs with empty requestid inside webClient calling:

2022-07-28 15:01:20.128 requestid[7fa703d7-5d99-4502-b3cf-0e4737a2d7be] INFO Before request
2022-07-28 15:01:20.228 requestid[] ERROR Error during request
2022-07-28 15:01:20.328 requestid[] ERROR CustomExceptiomMsg

I can fix it through using MDC.getCopyOfContextMap() before webClient and MDC.setContextMap(copyOfContextMap) in each lambda but I`m looking for more right solution

Anton
  • 57
  • 8

0 Answers0