如何在CompletableFuture中保留slf4j MDC日志记录上下文?

mem*_*und 5 java slf4j mdc completable-future

执行async时CompletableFuture,父线程org.slf4j.MDC上下文以及上下文会丢失。

这很不好,因为我使用某种“鱼标签”来跟踪多个日志文件中一个请求的日志。

MDC.put("fishid", randomId())

问题:一般情况下,我该如何保留该ID CompletableFutures?

List<CompletableFuture<UpdateHotelAllotmentsRsp>> futures =
    tasks.stream()
        .map(task -> CompletableFuture.supplyAsync(
            () -> businesslogic(task))
        .collect(Collectors.toList());

List results = futures.stream()
    .map(CompletableFuture::join)
    .collect(Collectors.toList());

public void businesslogic(Task task) {
       LOGGER.info("mdc fishtag context is lost here");
}
Run Code Online (Sandbox Code Playgroud)

Bhu*_*han 15

我解决这个问题的最易读的方法如下 -

---------------线程工具类--------------------

public static Runnable withMdc(Runnable runnable) {
    Map<String, String> mdc = MDC.getCopyOfContextMap();
    return () -> {
        MDC.setContextMap(mdc);
        runnable.run();
    };
}

public static <U> Supplier<U> withMdc(Supplier<U> supplier) {
    Map<String, String> mdc = MDC.getCopyOfContextMap();
    return (Supplier) () -> {
        MDC.setContextMap(mdc);
        return supplier.get();
    };
}
Run Code Online (Sandbox Code Playgroud)

- - - - - - - -用法 - - - - - - -

CompletableFuture.supplyAsync(withMdc(() -> someSupplier()))
                 .thenRunAsync(withMdc(() -> someRunnable())
                 ....
Run Code Online (Sandbox Code Playgroud)

ThreadUtils 中的 WithMdc 必须重载以包含 CompletableFuture 接受的其他功能接口

请注意,withMdc() 方法是静态导入的,以提高可读性。

  • 感谢您的改进。这比我原来的答案更好,所以我会接受你的答案。即使仅使用一个“.supplyAsync()”语句,它也更加一致。 (2认同)

mem*_*und 6

最后,我创建了一个Supplier保留MDC. 如果有人有更好的想法,请随时发表评论。

public static <U> CompletableFuture<U> supplyAsync(Supplier<U> supplier, Executor executor) {
    return CompletableFuture.supplyAsync(new SupplierMDC(supplier), executor);
}

private static class SupplierMDC<T> implements Supplier<T> {
    private final Supplier<T> delegate;
    private final Map<String, String> mdc;

    public SupplierMDC(Supplier<T> delegate) {
        this.delegate = delegate;
        this.mdc = MDC.getCopyOfContextMap();
    }

    @Override
    public T get() {
        MDC.setContextMap(mdc);
        return delegate.get();
    }
}
Run Code Online (Sandbox Code Playgroud)