skip to content

SLF4J

The JVM logging facade you compile against, bound to a real implementation at deployment time, with parameterised messages and MDC for context. Interviewers ask about facade versus binding because duplicate or missing bindings are one of the most common JVM startup problems.

on this pageshow

explore

questions

21

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?

level: juniorimportance: must knowfreq 60%

answer

  1. the thread outlives the request
  2. every exit path, exceptions included
  3. try-with-resources returns a Closeable
  4. close() removes, it does not restore
  5. one key versus the whole map

basics

~20 s

Put 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 lines
java
public 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

for a junior

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.

for a middle

Explain that MDCCloseable.close() delegates to MDC.remove, so a nested scope on the same key deletes the outer value rather than restoring it.

for a senior

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.

for a principal

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.
open as a page

Why do SLF4J log calls use a message with `{}` placeholders and separate arguments instead of building the message with string concatenation, and when do you still need an `isDebugEnabled()` guard?

level: juniorimportance: must knowfreq 80%

basics

~20 s

Placeholders defer formatting: if the level is disabled, the arguments are never converted to strings and no message is built. Concatenation pays that cost on every call. You only need an enabled-check when computing an argument is itself expensive.

open as a page

What problem does the SLF4J logging facade solve on the JVM, and how does an application end up bound to one concrete logging backend at runtime?

level: middleimportance: must knowfreq 70%

basics

~20 s

SLF4J is an API-only jar that libraries compile against. At startup it discovers one provider on the classpath and delegates every call to it. The application, not the library, picks the backend; with no provider, logging becomes a no-op.

open as a page

With SLF4J's MDC, how do you carry a request id into ExecutorService tasks and CompletableFuture stages, and what must the task's finally do?

level: middleimportance: must knowfreq 55%

basics

~10 s

Capture MDC.getCopyOfContextMap() when the task is submitted, apply it with MDC.setContextMap inside the task, and in finally restore the worker's previous map, clearing when it was null, so no request's entries stay behind.

open as a page

In SLF4J 2.0, how does the formatter decide whether a log call's last argument is the exception to print with its stack trace?

level: middleimportance: must knowfreq 61%

basics

~20 s

When a call passes two or more arguments and the last is a Throwable, SLF4J 2.0 strips it off and logs it as the cause, however many {} anchors remain. An exception in any other position is a plain value, printed via toString().

open as a page

What do SLF4J 2.0's own startup lines, such as 'Actual provider is of type [...]', tell you, and what does slf4j.internal.verbosity change?

level: juniorimportance: should knowfreq 40%

basics

~10 s

SLF4J prints its own SLF4J(I)/SLF4J(W) lines to stderr about binding: no provider, several providers, and 'Actual provider is of type', naming the winner. slf4j.internal.verbosity (default INFO) filters those lines, never application logs.

open as a page

In SLF4J 2.0's fluent API, why does a logger.atWarn() chain that never calls log() print nothing, and when do you use setCause()?

level: juniorimportance: should knowfreq 40%

basics

~20 s

Builder methods such as addArgument and addKeyValue only record data on a pending event; log() hands it to the backend, so a chain without it logs nothing. setCause attaches the exception directly, not as a trailing argument.

open as a page

In SLF4J placeholder logging, how do you print a literal `{}` in a message, and how are null values and array arguments rendered?

level: juniorimportance: should knowfreq 52%

basics

~20 s

Put a backslash before the brace, written \{} in a Java string literal, and SLF4J prints {} without using up an argument. A null argument prints as null; arrays print as [a, b], except a reference-type array passed alone, which becomes the argument list.

open as a page

In SLF4J 2.0's fluent API, when is a Supplier passed to addArgument() or addKeyValue() actually invoked, and what still runs eagerly?

level: middleimportance: should knowfreq 35%

basics

~20 s

On a disabled level, atDebug() returns a no-op builder that never calls the Supplier. On an enabled level, DefaultLoggingEventBuilder calls get() at once inside addArgument or addKeyValue, not at formatting time. Plain argument expressions always run before the call.

open as a page

With jul-to-slf4j on the classpath, how do you install SLF4JBridgeHandler so java.util.logging records reach SLF4J, and how are JUL levels mapped?

level: middleimportance: should knowfreq 38%

basics

~10 s

Call SLF4JBridgeHandler.removeHandlersForRootLogger(), then SLF4JBridgeHandler.install(), once at startup, or name the handler in logging.properties. FINEST maps to TRACE, FINER and FINE to DEBUG, CONFIG and INFO to INFO, WARNING to WARN, SEVERE to ERROR.

open as a page

What is SLF4J's Mapped Diagnostic Context (MDC), and why does putting a correlation identifier into it often produce missing or wrong values in a service that uses thread pools and asynchronous work?

level: middleimportance: should knowfreq 55%

basics

~20 s

MDC is a per-thread key-value map that the layout can print on every line, so you set a correlation id once instead of passing it to every log call. It is thread-local: work handed to another thread does not inherit it, and a pooled thread keeps stale entries unless cleared.

open as a page

A service upgraded from SLF4J 1.7 to slf4j-api 2.0 stopped writing application logs while its 1.7-era binding jar is still deployed; how do you diagnose and fix it?

level: seniorimportance: should knowfreq 48%

basics

~10 s

slf4j-api 2.0 finds backends only through ServiceLoader and ignores 1.7-era StaticLoggerBinder bindings, so it falls back to a no-op logger and prints 'Ignoring binding found at'. Replace the binding with the backend's 2.0 provider.

open as a page

A payments team's SLF4J 2.0 addKeyValue() pairs print as `orderId=42 Payment captured` on one backend but as separate fields on another; why?

level: seniorimportance: should knowfreq 28%

basics

~20 s

DefaultLoggingEventBuilder hands the whole event to a Logger that implements LoggingEventAware; for any other Logger it prefixes markers and key=value text to the message and calls the classic API. Only an event-aware logger receives the pairs as data.

open as a page

Third-party dependencies in a JVM service log through java.util.logging, Apache Commons Logging and Log4j 1.x, yet operations wants a single log stream. How do the SLF4J bridge jars solve this, and what must you avoid when installing them?

level: seniorimportance: should knowfreq 45%

basics

~20 s

Bridge jars re-implement each legacy API on top of SLF4J so those calls land in your one backend. Rules: never ship both a bridge and the binding that routes back to the same framework (infinite loop), and exclude the original legacy jar.

open as a page

A Spring Boot service embeds one library logging through Log4j 1 and another through the Log4j 2 API; which Log4j-related SLF4J jars do you ship when the backend is Logback, and when it is Log4j 2?

level: seniorimportance: should knowfreq 32%

basics

~20 s

On Logback, ship log4j-over-slf4j for Log4j 1 calls and log4j-to-slf4j for Log4j 2 API calls. On Log4j 2, keep log4j-over-slf4j but bind SLF4J with log4j-slf4j2-impl and drop log4j-to-slf4j. Never pair a jar with its reverse.

open as a page

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?

level: seniorimportance: should knowfreq 35%

basics

~10 s

SLF4J'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.

open as a page

On an inventory service's hot path, what does a disabled SLF4J `log.debug` call with four arguments still cost, and how would you measure that cost?

level: seniorimportance: should knowfreq 44%

basics

~20 s

The call still evaluates every argument expression, boxes primitive arguments and, with three or more arguments, allocates the varargs Object[] before the level check runs. Measure it with a JMH benchmark using the GC profiler, and JFR allocation sampling in production.

open as a page

What SLF4J dependency rule would you set for every library and service in an organisation, and how would you make the build enforce it?

level: principalimportance: should knowfreq 30%

basics

~20 s

Libraries depend on slf4j-api only; each application ships exactly one provider at runtime scope and no 1.7-era binding. Because SLF4J merely warns or goes silent, a build check counting providers and StaticLoggerBinder resources must enforce it.

open as a page

In SLF4J 2.0.9 and later, what does the slf4j.provider system property do, and why is it a stopgap rather than a fix?

level: middleimportance: nice to knowfreq 35%

basics

~20 s

slf4j.provider names one SLF4JServiceProvider class; if it instantiates, SLF4J skips ServiceLoader discovery. If it fails, SLF4J prints an error and falls back to discovery. The extra provider stays on the classpath, so it masks the problem.

open as a page

SLF4J 2.0 added a fluent logging API entered through methods such as `atInfo()` and `atDebug()`. What does it offer over the classic `info(String, Object...)` calls, and how do its key-value pairs differ from Mapped Diagnostic Context entries and from Markers?

level: middleimportance: nice to knowfreq 25%

basics

~20 s

The fluent API builds an event step by step: message, arguments, key-value pairs, a marker, a cause, then log. Its key-value pairs are per-event structured fields; MDC entries are per-thread ambient context; markers are labels for routing and filtering, not data.

open as a page

In SLF4J 2.0, how do calls to the JDK's System.Logger reach SLF4J, and does a Spring application still need jcl-over-slf4j for Commons Logging?

level: middleimportance: nice to knowfreq 27%

basics

~10 s

Add slf4j-jdk-platform-logging: its SLF4JSystemLoggerFinder is the JDK's System.LoggerFinder service and hands every System.Logger to SLF4J. Spring Framework 7.0.9's spring-core already depends on Apache commons-logging 1.3.5, so check that before adding jcl-over-slf4j.

open as a page