skip to content

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%

answer

  1. builder methods return a builder
  2. one terminal method
  3. an annotation on the chain methods
  4. a dedicated slot for the exception
  5. trailing argument is only a fallback

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.

solid answer

~50 s

A fluent call starts at a level method such as `atWarn()` or `atLevel(Level.WARN)` on the ordinary `Logger`, adds content with `setMessage`, `addArgument`, `addKeyValue`, `addMarker` and `setCause`, and ends with `log()` or an overload such as `log("Retry {} failed", attempt)`. Every intermediate method returns a `LoggingEventBuilder` and writes nothing; the Javadoc of `log()` says it must be called for logging to occur, and that without it an event is built but nothing is logged. Those methods carry `@CheckReturnValue`, so an IDE inspection for ignored results can flag a dropped chain. `setCause(Throwable)` puts the exception in the event's cause slot, which every dispatch path in the default builder hands over as the cause; an exception passed as the last argument instead sits in the argument list and becomes the cause only where the trailing-throwable rule is applied.

code

java · 8 lines
java
// Bug: builds an event and drops it
logger.atError().setCause(ex).setMessage("Capture failed for {}");

// Fixed: the chain ends in log(), and setCause carries the exception
logger.atError()
      .setCause(ex)
      .addArgument(paymentId)
      .log("Capture failed for {}");

go deeper

for a junior

Recall the shape: a level method such as atInfo(), content methods, then log(). Say plainly that without log() nothing is written, and that setCause() is how the fluent API attaches an exception.

for a middle

Explain that each content method only records data on a DefaultLoggingEvent and returns the builder, that @CheckReturnValue lets an IDE flag a dropped chain, and that setCause fills the cause slot while a trailing argument relies on a heuristic.

for a senior

Show that you would catch a dropped chain in review or with an inspection, and that you standardise on setCause so stack traces survive on every provider instead of depending on the trailing-argument rule.

for a principal

Weigh whether to make the fluent style the house default: it pays where events carry key-value pairs, but each chain is one more place to forget log(), so pair the convention with an enforced inspection.

## What a fluent call is SLF4J 2.0 added a second way to write a log statement. Instead of one method call such as `logger.warn("Retry {} failed", attempt, ex)`, you build a **logging event** piece by piece and then emit it. The methods that start a chain are **default methods on the ordinary `org.slf4j.Logger` interface**, the same object `LoggerFactory.getLogger(...)` already returns: - `atTrace()`, `atDebug()`, `atInfo()`, `atWarn()` and `atError()` start a builder at a fixed level. - `atLevel(Level level)` starts one at a level chosen at runtime, using the `org.slf4j.event.Level` enum (`ERROR`, `WARN`, `INFO`, `DEBUG`, `TRACE`). Each returns an `org.slf4j.spi.LoggingEventBuilder`. When the level is enabled the default is a fresh `DefaultLoggingEventBuilder`; when it is disabled you get the shared `NOPLoggingEventBuilder` singleton, which ignores everything handed to it. ## The three kinds of builder method 1. **Content methods** record data on the pending event and return a builder: `setMessage(String)`, `setMessage(Supplier<String>)`, `addArgument(Object)`, `addArgument(Supplier<?>)`, `addKeyValue(String, Object)`, `addKeyValue(String, Supplier<Object>)`, `addMarker(Marker)` and `setCause(Throwable)`. 2. **The terminal method** `log()` performs the logging and returns `void`. 3. **Shortcut terminals** combine the two: `log(String)`, `log(String, Object)`, `log(String, Object, Object)`, `log(String, Object...)` and `log(Supplier<String>)`. The interface documents `log(String, Object)` as equivalent to `setMessage`, then `addArgument`, then `log()`. A typical statement reads top to bottom: ```java logger.atWarn() .addKeyValue("orderId", orderId) .setCause(ex) .log("Payment retry {} failed", attempt); ``` ## Why a chain without log() prints nothing The content methods do not write anything. In `DefaultLoggingEventBuilder` each one adds to a `DefaultLoggingEvent` held by the builder: an argument goes on one list, a key-value pair on another, a marker on a third. Only `log()` or a `log(...)` overload passes that event to the bound logger. The Javadoc on `log()` says it plainly: the method must be called for logging to occur, and if the call is omitted an event is built but no logging occurs. So this compiles and does nothing: ```java logger.atInfo().addKeyValue("orderId", orderId).setMessage("Paid"); ``` There is no flush when the builder goes out of scope and nothing on garbage collection; the event simply becomes unreachable. To make the mistake visible, every builder-returning method in `LoggingEventBuilder` is annotated with `org.slf4j.helpers.CheckReturnValue` (since 2.0.0-beta1). Its Javadoc says such methods should be followed by one of the terminating `log()` methods, and an IDE inspection for ignored method results that recognises an annotation of that name can warn when the returned builder is discarded. The Java compiler itself does not enforce it. Dropped chains usually come from ordinary code changes rather than typos: - a refactor deletes the last line of a multi-line chain, the one holding `log(...)`; - a helper returns a `LoggingEventBuilder` with common pairs already added, and a caller forgets to finish it; - a conditional adds a pair in one branch and calls `log()` only in the other. In each case the code compiles, tests that do not assert on log output pass, and the line is missing exactly when someone needs it. ## setCause versus a trailing exception In the classic API you attach an exception by passing it as the **last argument**, a rule covered with placeholder formatting. The fluent API adds a dedicated slot. | Form | Where the exception lands | |---|---| | `setCause(ex)` | the event's throwable field, set directly | | `addArgument(ex)` last, or `log("msg {}", a, ex)` | the argument list; it becomes the cause only where the trailing-throwable rule is applied | `setCause` is the unambiguous choice. A logger that receives the whole event reads the cause from `getThrowable()`, and the fallback path in `DefaultLoggingEventBuilder` appends the cause after the other arguments so that the classic method treats it as the cause. An exception left in the argument list depends on a heuristic: SLF4J's own adapters apply it through `NormalizedParameters`, but only when no cause was set. Two details worth knowing: - `setCause` **replaces**: it sets one field, so calling it twice keeps the second exception. - If you set a cause and also pass an exception as the last argument, SLF4J's own code paths keep the cause and treat the extra exception as an ordinary argument, so its stack trace is not printed. ## Habits that keep fluent calls correct - End every chain with `log()` or a `log(...)` overload in the same statement. - Build one chain per log statement; never keep a builder in a field, because each one accumulates the arguments and pairs added to it. - Use `setCause` for the exception and keep the placeholders for values. - Turn on the inspection for ignored method results so a dropped chain shows up in review rather than as a missing line during an incident.

  • Can you keep the builder returned by atInfo() in a field and reuse it for later log lines?
    You should not. On an enabled level each `atInfo()` call creates a new `DefaultLoggingEventBuilder` around one event, and `addArgument` and `addKeyValue` append to that event's lists, so a reused builder carries every earlier argument and pair into the next line. On a disabled level you get the shared `NOPLoggingEventBuilder` singleton instead. Build one chain per statement and end it with `log()`.
  • What happens if you call setCause() and also pass an exception as the last log() argument?
    `setCause` fills the event's throwable slot, so that exception is the cause. SLF4J's own paths then leave the other exception in the argument list: `NormalizedParameters` looks for a trailing throwable only when no cause is set, and the fallback path appends the cause after all arguments. The extra exception fills a `{}` if one is free and is otherwise ignored, without a stack trace.
  • How do you pick the level at runtime with the fluent API?
    Call `atLevel(Level)` with an `org.slf4j.event.Level` value. It returns a real builder when `isEnabledForLevel(level)` is true and the no-op singleton otherwise, so a wrapper or a configurable audit hook can log at a level held in a variable without a switch over `atInfo()`, `atWarn()` and the rest.

  • addKeyValue writes the pair to the log by itself, before log() is called.
  • A chain without log() is flushed when the builder goes out of scope.
  • setCause and a trailing exception argument behave identically on every code path.
  • The fluent API needs a special logger type rather than the one LoggerFactory.getLogger returns.
  • Calling setCause twice attaches both exceptions to the same event.

Assumes SLF4J 2.0.20; the fluent LoggingEventBuilder API arrived in the 2.0 line and does not exist in 1.7.