MDC

152 阅读1分钟

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:

  1. We get a thread from the thread pool.
  2. Then we store some contextual information in MDC using MDC.put() or ThreadContext.put() .
  3. We use this information in some logs, and somehow we forgot to clear the MDC context.
  4. The borrowed thread comes back to the thread pool.
  5. After a while, the application gets the same thread from the pool.
  6. Since we didn’t clean up the MDC last time, this thread still owns some data from the previous execution.

参考