A service on SLF4J 2.0 calls MDC.put on every request, yet the request id never reaches its logs and nothing errors; how does the provider's MDCAdapter explain that?
answer
- MDC is only a front door
- the provider hands over the adapter
- simple and nop store nothing
- jdk14 stores but never prints
- stacks live apart from the map
basics
~10 sSLF4J's MDC only delegates to the MDCAdapter the bound provider supplies. slf4j-simple, slf4j-nop and the no-provider fallback supply NOPMDCAdapter, which discards every put, so MDC silently does nothing; check which provider bound.
solid answer
~40 s`MDC` keeps one `MDCAdapter`, taken from the bound `SLF4JServiceProvider` when `LoggerFactory` binds, and every static method delegates to it. `slf4j-simple` and `slf4j-nop` return `NOPMDCAdapter`, as does the fallback used when SLF4J reports `No SLF4J providers were found.`, so `put` stores nothing and `get` returns `null`, with no warning. `slf4j-jdk14` installs `BasicMDCAdapter`, which does store entries, but its logger adapter never reads MDC when it hands a record to java.util.logging, so the id does not appear unless your own code reads it back. `slf4j-reload4j` delegates to Log4j 1's MDC, and Logback's provider to Logback's own MDC; there the backend layout must print the key. Diagnose by printing `MDC.getMDCAdapter().getClass().getName()` or running with `-Dslf4j.internal.verbosity=DEBUG`.
code
java · 11 linespublic final class MdcSelfCheck {
private static final Logger log = LoggerFactory.getLogger(MdcSelfCheck.class);
public static void report() {
String adapter = MDC.getMDCAdapter().getClass().getName();
MDC.put("mdcProbe", "1");
boolean stored = "1".equals(MDC.get("mdcProbe"));
MDC.remove("mdcProbe");
log.info("MDC adapter {} stores values: {}", adapter, stored);
}
}go deeper
Recall that MDC needs a provider with MDC support, and that slf4j-simple and slf4j-nop silently ignore it.
Explain that MDC delegates to an MDCAdapter supplied by the bound SLF4JServiceProvider, and name which adapter each SLF4J-project provider installs.
Diagnose from symptoms: lines without ids under slf4j-simple, values that MDC.get returns but slf4j-jdk14 never prints, and stacks a context-map wrapper does not carry.
Decide which provider each deployable binds, and add a startup self-check so a provider meant for tests and tools, such as slf4j-simple, never reaches production unnoticed.
## MDC is a facade over an adapter In SLF4J, `org.slf4j.MDC` holds no map of its own. It keeps a single **`MDCAdapter`**, the interface in `org.slf4j.spi` that defines `put`, `get`, `remove`, `clear`, `getCopyOfContextMap`, `setContextMap` and, since 2.0.0, the stack methods `pushByKey`, `popByKey`, `getCopyOfDequeByKey` and `clearDequeByKey`. Every static method on `MDC` forwards to that adapter. The adapter comes from the **provider**, the `SLF4JServiceProvider` that `LoggerFactory` bound at startup: during binding, `LoggerFactory` asks the provider for `getMDCAdapter()` and, when that is already non-null, installs it before calling the provider's `initialize()`. Since 2.0.17, `MDC.getMDCAdapter()` also fetches the adapter from the provider itself if none was set yet. So what `MDC.put` does is decided entirely by which provider is on the classpath. SLF4J's own class documentation says it plainly: if the underlying logging system offers MDC, SLF4J's MDC delegates to it; for java.util.logging, which lacks MDC, `BasicMDCAdapter` is used; for `slf4j-simple` and `slf4j-nop`, `NOPMDCAdapter` is used. ## What each provider in the SLF4J project installs | Provider artifact | Adapter | Effect of `MDC.put` | |---|---|---| | `slf4j-simple` | `NOPMDCAdapter` | discarded; `get` returns `null` | | `slf4j-nop` | `NOPMDCAdapter` | discarded | | none found (NOP fallback) | `NOPMDCAdapter` | discarded | | `slf4j-jdk14` | `BasicMDCAdapter` | stored per thread, not printed by the provider | | `slf4j-reload4j` | `Reload4jMDCAdapter` | delegated to Log4j 1's `MDC` | Logback and Log4j 2 ship their own SLF4J providers in their own artifacts, and those delegate to the backend's MDC; what they print is the backend's layout configuration, outside SLF4J. ## Why nothing errors `NOPMDCAdapter` implements every method as an empty body or a `return null`. `MDC.put` validates the key, finds a non-null adapter and delegates, so no exception is thrown and nothing reports that the value was dropped. The clues are at startup: - with no provider at all, SLF4J warns `No SLF4J providers were found.` and `Defaulting to no-operation (NOP) logger implementation`, and then logging itself is off too; - with `slf4j-simple` bound, logging works and only MDC is dead, which is the confusing case: lines appear, ids do not; - with several providers on the classpath, SLF4J warns `Class path contains multiple SLF4J providers.` and prints `Actual provider is of type [...]`, and the one it picked may not be the one you meant. This is why the symptom tends to appear after a dependency change rather than a code change. A provider meant for tests or command-line tools lands on the runtime classpath, or the intended backend's provider drops out in a build change, and the service keeps logging through whatever provider is left. Every line still prints, so nobody notices until someone searches the logs by request id and finds nothing. ## The slf4j-jdk14 trap `BasicMDCAdapter` really stores entries, in an `InheritableThreadLocal` that copies the map into threads created afterwards, so `MDC.get` returns your value and a unit test of the filter passes. But nothing in `slf4j-jdk14`'s logger adapter reads MDC when it converts a call into a java.util.logging record, so the entries reach output only if code of your own reads them back from `MDC`. Seeing `get` succeed proves the adapter stores values; it says nothing about the output. ## The 2.0 stacks `MDC.pushByKey(key, value)` and `MDC.popByKey(key)` keep a **stack of values per key**. In SLF4J's own `BasicMDCAdapter` and `Reload4jMDCAdapter` the stacks live in a separate `ThreadLocalMapOfStacks`, apart from the key-value map, which has consequences: - `getCopyOfContextMap()` and `setContextMap()` do not include them, so an executor wrapper built on those two methods does not carry stacks to the worker; - `MDC.clear()` empties only the map; a stack is emptied by popping it or by `MDC.getMDCAdapter().clearDequeByKey(key)`, since `MDC` has no static `clearDequeByKey`; - in 2.0.20, `MDC.getCopyOfDequeByKey` is declared without `static` on a class whose constructor is private, so in practice it is reached through `MDC.getMDCAdapter()` too; - `NOPMDCAdapter` discards pushes like everything else. ## A diagnosis order 1. Print `MDC.getMDCAdapter().getClass().getName()` once at startup; `NOPMDCAdapter` ends the search. 2. Or start with `-Dslf4j.internal.verbosity=DEBUG`, so `LoggerFactory` prints `Connected with provider of type [...]`. 3. Read the startup lines for missing or multiple providers. 4. If the adapter is real, check that the bound backend's layout prints the key, then check threading.
- How do you confirm at runtime which MDCAdapter SLF4J bound, without inspecting the classpath?Log `MDC.getMDCAdapter().getClass().getName()` once at startup, or run with `-Dslf4j.internal.verbosity=DEBUG` so `LoggerFactory` prints `Connected with provider of type [...]`. When several providers are found, SLF4J prints `Actual provider is of type [...]` even at its default verbosity. A `NOPMDCAdapter` in that output explains every missing id at once.
- Why does MDC.clear() leave values pushed with MDC.pushByKey in place, and how do you empty a stack?In SLF4J's `BasicMDCAdapter` and `Reload4jMDCAdapter` the stacks live in a separate per-thread structure, and `clear()` empties only the key-value map. Pop each value with `MDC.popByKey`, or call `clearDequeByKey(key)` on `MDC.getMDCAdapter()`: `MDC` has no static `clearDequeByKey`.
MDC is a mail slot in a door, and the provider decides what is behind it. With Logback or reload4j there is a box behind it that the layout can read from; with slf4j-simple the slot opens onto the street, so letters go in without a sound and are never seen again.
- If MDC.put does not throw, the entry must have been stored somewhere.
- slf4j-api falls back to BasicMDCAdapter when the provider has no MDC support.
- slf4j-jdk14 discards MDC entries exactly as slf4j-simple does.
- MDC.clear() also empties the stacks written with MDC.pushByKey.
- SLF4J keeps its own MDC map and every backend simply reads it.
Assumes SLF4J 2.0.20; providers supply the MDCAdapter through SLF4JServiceProvider, and pushByKey and popByKey date from 2.0.0.