0

I am using MDC Logger, which works correctly everywhere apart from when I'm sending a request using HttpClient async. The MDC data is not getting passed to next thread and which means they are not on ours logs. How am I able to get the new thread to have the MDC headers?

 java.net.http.HttpClient.newHttpClient()
                .sendAsync(request, HttpResponse.BodyHandlers.ofString())
                .thenApply(restLogging::logResponse)
                .thenApply(response -> handleResponse(url, responseTypeClass, objectMapper, response));
Zabuzard
  • 25,064
  • 8
  • 58
  • 82
wolfe111
  • 51
  • 2
  • Copy it to the new thread. The MDC is, as you noticed, thread bound so you will need to copy it. – M. Deinum Feb 04 '21 at 11:20
  • How do you copy it to the new thread? I've seen examples where you have a withMdc wrapper and use it like `CompletableFuture.supplyAsync(withMdc(() ->` but in this case the HttpClient.sendAsync is the one creating the CompletableFuture? – wolfe111 Feb 04 '21 at 11:33

1 Answers1

2

MDC context needs to propagated to the async method as it will be running in different threads.

call it like

java.net.http.HttpClient.newHttpClient()
            .sendAsync(request, HttpResponse.BodyHandlers.ofString())
            .thenApply(restLogging::logResponse)
            .thenApply(response -> handleResponse(url, responseTypeClass, objectMapper, response, MDC.getCopyOfContextMap()));

below implementation:

handleResponse(url, responseTypeClass, objectMapper, response, Map<String,String> mdcContextMap){
MDC.setContextMap(mdcContextMap);
//your business logic
MDC.clear(); }
Mervin
  • 31
  • 4