【问题标题】:HttpClient sendAsync losing MDC logging informationHttpClient sendAsync 丢失 MDC 日志信息
【发布时间】:2021-02-04 11:14:57
【问题描述】:

我正在使用 MDC Logger,除了我使用 HttpClient 异步发送请求时,它在任何地方都能正常工作。 MDC 数据没有传递到下一个线程,这意味着它们不在我们的日志中。我怎样才能让新线程拥有 MDC 标头?

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

【问题讨论】:

  • 复制到新线程。如您所见,MDC 是线程绑定的,因此您需要复制它。
  • 如何将其复制到新线程?我见过一些例子,你有一个 withMdc 包装器并像CompletableFuture.supplyAsync(withMdc(() -> 一样使用它,但在这种情况下,HttpClient.sendAsync 是创建 CompletableFuture 的那个?

标签: java completable-future mdc java-http-client


【解决方案1】:

MDC 上下文需要传播到异步方法,因为它将在不同的线程中运行。

这样称呼

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

下面的实现:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-14
    • 2020-08-07
    • 2019-11-17
    • 2020-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多