java MDC_java – 如何使用线程池的MDC?

是的,这是我遇到的常见问题。有几个解决方法(如手动设置它,如描述),但理想情况下,你想要一个解决方案

>一致地设置MDC;

>避免默认的错误,MDC是不正确的,但你不知道它;和

>最小化对如何使用线程池的更改(例如,将Callable与MyCallable无处不在,或类似的丑陋)。

这里有一个我使用的解决方案,满足这三个需求。代码应该是不言自明的。

(注意,这个执行器可以被创建并馈送到Guava的MoreExecutors.listeningDecorator(),if

你使用Guava的ListanableFuture。)

import org.slf4j.MDC;

import java.util.Map;

import java.util.concurrent.*;

/**

* A SLF4J MDC-compatible {@link ThreadPoolExecutor}.

*

* In general, MDC is used to store diagnostic information (e.g. a users session id) in per-thread variables, to facilitate

* logging. However, although MDC data is passed to thread children, this doesnt work when threads are reused in a

* thread pool. This is a drop-in replacement for {@link ThreadPoolExecutor} sets MDC dat

是的,这是我遇到的常见问题。有几个解决方法(如手动设置它,如描述),但理想情况下,你想要一个解决方案 >一致地设置MDC; >避免默认的错误,MDC是不正确的,但你不知道它;和 >最小化对如何使用线程池的更改(例如,将Callable与MyCallable无处不在,或类似的丑陋)。 这里有一个我使用的解决方案,满足这三个需求。代码应该是不言自明的。 (注意,这个执行器可以被创建并馈送到Guava的MoreExecutors.listeningDecorator(),if 你使用Guava的ListanableFuture。) import org.slf4j.MDC; import java.util.Map; import java.util.concurrent.*; /** * A SLF4J MDC-compatible {@link ThreadPoolExecutor}. * * In general, MDC is used to store diagnostic information (e.g. a users session id) in per-thread variables, to facilitate * logging. However, although MDC data is passed to thread children, this doesnt work when threads are reused in a * thread pool. This is a drop-in replacement for {@link ThreadPoolExecutor} sets MDC dat
经验分享 程序员 微信小程序 职场和发展