MDC概述
Mapped Diagnostic Context(MDC)主要是在打印日志的时候,在当前代码的上文中不存在要打印的变量,而又需要打印该变量的数据。在这种需求场景下就可以通过 MDC 来解决。
MDC的注意点
MDC是基于ThreadLocal 实现的。因此在多线程环境下,在 MDC 用完后,需要 clear。
Let’s see how the combination of ThreadLocal-based MDCs and thread pools can be dangerous:
- We get a thread from the thread pool.
- Then we store some contextual information in MDC using MDC.put() or ThreadContext.put() .
- We use this information in some logs, and somehow we forgot to clear the MDC context.
- The borrowed thread comes back to the thread pool.
- After a while, the application gets the same thread from the pool.
- Since we didn’t clean up the MDC last time, this thread still owns some data from the previous execution.