In SLF4J, how does a servlet filter scope an MDC request id to one request, and when should it use MDC.remove versus MDC.clear?
answer
- the thread outlives the request
- every exit path, exceptions included
- try-with-resources returns a Closeable
- close() removes, it does not restore
- one key versus the whole map
basics
~20 sPut the id with MDC.putCloseable inside try-with-resources, or call MDC.remove in a finally block, so the entry leaves the thread when the request ends. remove drops only your key; clear wipes every entry on the thread.
solid answer
~40 s`MDC.put(key, value)` writes into the current thread's diagnostic map, and the container hands that thread to the next request, so the filter must take the entry out itself. `MDC.putCloseable(key, value)` puts the value and returns an `MDC.MDCCloseable` whose `close()` calls `MDC.remove(key)`; wrapping `chain.doFilter(...)` in try-with-resources removes it on every exit path, an exception included. `close()` removes the key, it does not restore a value the key held before. Use `remove(key)` when you own one key and other filters may have put entries of their own; reserve `clear()` for a boundary that owns the whole map, because it empties every entry on the thread, including ones code further out still logs.
code
java · 12 linespublic class RequestIdFilter implements Filter {
private static final String KEY = "requestId";
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
String id = UUID.randomUUID().toString();
try (MDC.MDCCloseable ignored = MDC.putCloseable(KEY, id)) {
chain.doFilter(request, response);
}
}
}go deeper
Recall the pair: putCloseable inside try-with-resources, or put plus remove in finally. Say that the container reuses threads, so leftover entries outlive the request.
Explain that MDCCloseable.close() delegates to MDC.remove, so a nested scope on the same key deletes the outer value rather than restoring it.
Show how shared request threads make clear() dangerous in inner code, and say which boundary is allowed to own the whole map in your services.
Set the team rule: libraries never call clear, applications clear once at the outermost boundary, and request keys are named so scopes never collide.
## What the filter is doing The **Mapped Diagnostic Context** (MDC) in SLF4J is a map of string keys to string values that belongs to the current thread. A servlet filter is the usual place to fill it: it runs before the controller, so a request id put there appears on every line the request logs, provided the bound backend's layout prints that key. The catch is the end of the request. The servlet container serves many requests on a small set of reused threads, and SLF4J never empties the map for you. Whatever the filter puts in, the filter has to take out. The static methods involved, all on `org.slf4j.MDC`: - `MDC.put(key, value)` stores one entry for the current thread. A `null` key throws `IllegalArgumentException`; whether a `null` value is accepted depends on the bound provider. - `MDC.get(key)` reads one entry back. - `MDC.remove(key)` deletes one entry and does nothing if the key is absent. - `MDC.clear()` deletes every entry the current thread holds. - `MDC.putCloseable(key, value)` calls `put` and returns an `MDC.MDCCloseable`. ## putCloseable and try-with-resources `MDC.MDCCloseable` is a small nested class that implements `java.io.Closeable`. It remembers the key, and its `close()` method calls `MDC.remove(key)`. That makes the entry's lifetime a block of code: 1. The filter creates the id and calls `MDC.putCloseable("requestId", id)` in the resource clause of a try-with-resources statement. 2. The body calls `chain.doFilter(request, response)`, so every line logged on this thread during the request carries the id. 3. When the block exits, normally or by an exception, Java calls `close()`, and the key is removed. The same effect without the helper is `MDC.put` before the `try` and `MDC.remove` in `finally`. What does not work is a `remove` placed after `chain.doFilter(...)` outside `finally`: if the chain throws, that line never runs and the entry stays on the thread. One detail surprises people: **`close()` removes the key, it does not put back the previous value**. If an outer filter had already stored `requestId` and an inner block calls `putCloseable` with the same key, the outer value is gone once the inner block closes. Either use distinct keys, or save the old value with `MDC.get` and restore it yourself in `finally`. ## remove versus clear | Call | What it deletes | Use it when | |---|---|---| | `MDC.remove(key)` | one entry | your code put that one key | | `MDCCloseable.close()` | one entry, through `remove` | you used `putCloseable` | | `MDC.clear()` | every entry on the thread | the code owns the whole map | Several pieces of code often share one thread's map during a request: a request-id filter, a security filter that adds a user id, a tenant filter. If the innermost one calls `clear()` on its way out, the outer filters' later log lines lose their entries too. So: - **inner filters and helpers** remove exactly the keys they put; - **the outermost boundary**, the first filter in the chain or the code that owns the thread, may call `clear()` as a final safety net, because nothing further out still expects an entry; - **library code** should never call `clear()`, since it cannot know what the application has stored. ## Putting it in the chain Where the filter sits matters as much as how it cleans up: - register it **ahead of** other filters that log, so their lines carry the id too; - keep the key name in one constant that matches the layout configuration of the bound backend, because a misspelt key on either side gives an empty field and no error; - test it with a fake chain that records `MDC.get("requestId")`: the value must be set inside the chain and `null` once `doFilter` returns, on the normal path and when the chain throws. ## Common mistakes - Putting the id and never removing it, on the belief that the request's end tidies up. - Removing it outside `finally`, so an exception skips the cleanup. - Calling `clear()` deep inside the request and wiping entries other code logs later. - Expecting `putCloseable` to restore an earlier value of the same key. - Passing a `null` key, which throws `IllegalArgumentException` rather than being ignored. None of this carries the id onto other threads. A task handed to an executor runs with that worker thread's own map; copying entries across is a separate step that the filter does not do.
- An outer filter already put requestId, and an inner block calls MDC.putCloseable with the same key. What does the outer filter see after the inner block closes?No value at all. `MDCCloseable.close()` calls `MDC.remove(key)`, so the key is deleted rather than restored to the outer filter's value, and the outer filter's later lines lose the id. Use a distinct key for the inner scope, or save the old value with `MDC.get` and put it back in `finally`.
- Does SLF4J's MDC.put accept null for the key or for the value?Not for the key: `MDC.put` throws `IllegalArgumentException` when the key is `null`. For the value, the API leaves it to the provider: its documentation says a `null` value is allowed only if the underlying implementation supports it. SLF4J's own `BasicMDCAdapter` stores a `null` value; other providers may refuse it.
- Closing the MDCCloseable from putCloseable restores the key's previous value.
- MDC entries are removed automatically when the HTTP request finishes.
- Calling MDC.remove after chain.doFilter, outside finally, is enough cleanup.
- Every filter should call MDC.clear() on its way out, just to be safe.
- MDC.put with a null key is silently ignored.