In SLF4J 2.0's fluent API, when is a Supplier passed to addArgument() or addKeyValue() actually invoked, and what still runs eagerly?
answer
- the level check comes first
- a singleton that ignores its inputs
- get() at the add call
- arguments are evaluated before the call
- backend filters come too late
basics
~20 sOn 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.
solid answer
~40 s`atDebug()` checks `isDebugEnabled()` once. If the level is off it returns `NOPLoggingEventBuilder.singleton()`, whose methods ignore their inputs, so a `Supplier` given to `addArgument(Supplier<?>)`, `addKeyValue(String, Supplier<Object>)`, `setMessage(Supplier<String>)` or `log(Supplier<String>)` is never called. If the level is on, the default `DefaultLoggingEventBuilder` calls `get()` immediately inside that method and stores the result, so the work is not postponed to formatting or to any filtering the backend does later. What Java evaluates before a call still runs on both paths: the `atDebug()` chain itself and a plain argument such as `addKeyValue("total", sum(items))`. A supplier therefore saves work only on a disabled level, and only for values that cost something to compute.
go deeper
Recall that a disabled level gives you a no-op builder, and that a lambda passed to addArgument runs only when the level is on.
Explain both halves: atDebug() returns NOPLoggingEventBuilder when the level is off, while DefaultLoggingEventBuilder calls get() at once inside addArgument or addKeyValue when it is on, and plain argument expressions always run first.
Show the production consequence: suppliers save nothing on an enabled level or when a backend filter drops the event later, and a side effect inside one turns a log-level change into a behaviour change.
Decide whether a team rule should require suppliers only for costly values, weighing lambdas scattered through every statement against the measured cost of the few that compute something expensive.
## Two separate sources of laziness The fluent API's laziness comes from two different places, and confusing them produces wrong cost estimates. 1. **The level check at the start of the chain.** `Logger.atDebug()` is a default method that calls `isDebugEnabled()`. If the level is enabled it returns `makeLoggingEventBuilder(DEBUG)`, which by default creates a new `DefaultLoggingEventBuilder`; if not, it returns `NOPLoggingEventBuilder.singleton()`. `atLevel(Level)` does the same through `isEnabledForLevel(level)`. 2. **The Supplier overloads.** `addArgument(Supplier<?>)`, `addKeyValue(String, Supplier<Object>)`, `setMessage(Supplier<String>)` and `log(Supplier<String>)` accept a function that produces the value instead of the value itself. They combine in only one way: a supplier skips work **when the builder is the no-op one**. ## What the no-op builder does `NOPLoggingEventBuilder` implements every content method as "return the singleton" and every `log` method with an empty body. It never touches the `Supplier` it is given, so the code inside the lambda never runs and no event object is built. This is the case the overloads were designed for: a disabled statement costs one level check plus whatever Java must evaluate to make the calls. ## What the real builder does On an enabled level the default `DefaultLoggingEventBuilder` handles the chain, and it is **not lazy past that point**. Its `addArgument(Supplier<?>)` calls `objectSupplier.get()` on the spot and stores the result; `addKeyValue(String, Supplier<Object>)` and `setMessage(Supplier<String>)` do the same. The value is computed when that method is called: before `log()`, before any formatting, and before the backend sees the event. Consequences: - On an enabled level, a supplier costs the same work as passing the value directly, plus the lambda. - A backend may still discard the event after receiving it; the `LoggingEventAware` Javadoc says implementations may apply further filtering. By then every supplier has already run. - Each supplier runs once per statement, at its own call, in the order the chain is written. This describes the API's default builder. A provider may override `makeLoggingEventBuilder` with its own builder; none of the providers in SLF4J's own repository does, and the wrappers there that override it delegate to the wrapped logger. The shortcut terminals follow the same rule as plain calls. `log(String, Object...)` takes values, not suppliers, so anything passed there is evaluated before the call; to defer one argument, add it with `addArgument(Supplier<?>)` and finish with `log(String)`. `setMessage(Supplier<String>)` and `log(Supplier<String>)` let a disabled level skip building the message text itself, which helps only when that text is assembled from something costly, such as a loop over a collection. ## What Java still evaluates eagerly Java evaluates a method's arguments before calling it, so some work happens on both paths: ```java logger.atDebug() .addKeyValue("total", sum(items)) // sum(items) always runs .addKeyValue("lines", () -> render(items)) // render runs only if DEBUG is on .log("Basket priced"); ``` `sum(items)` runs even when DEBUG is off, because the no-op builder only ever receives its result. The lambda expression `() -> render(items)` is evaluated too, which is cheap, but its body runs only on an enabled builder. The receiver chain, `logger.atDebug()` and each intermediate call, always runs. | Call | DEBUG disabled | DEBUG enabled | |---|---|---| | `addArgument(expensive())` | `expensive()` runs, result ignored | `expensive()` runs, result stored | | `addArgument(() -> expensive())` | body never runs | body runs inside `addArgument` | | `addKeyValue("k", () -> v())` | body never runs | body runs inside `addKeyValue` | | `log(() -> buildMessage())` | body never runs | body runs inside `log` | ## Rules that follow - Use a supplier when computing the value is genuinely costly: serialising a collection, summing a large list, rendering a diff. - Passing an object you already hold is cheap; its `toString()` runs only if the event is formatted. Wrapping such a reference in a supplier buys nothing. - Keep suppliers free of side effects. Whether they run depends on configuration, so a counter or cache update inside one changes program behaviour when someone changes a log level. - Do not count on a supplier to save work that a backend filter later throws away; only the level check in `atDebug()` or `atLevel()` gates it.
- Why is a supplier with a side effect, such as incrementing a counter, a bug?Because whether it runs depends on the configured level. On a disabled level the no-op builder never calls it, so the counter silently stops moving when someone turns DEBUG off; on an enabled level it runs once, inside `addArgument` or `addKeyValue`. Logging configuration should never change program behaviour, so keep suppliers pure and do the counting outside the log statement.
- Does the fluent API's laziness help when a backend filter rejects an event whose level is enabled?No. The level check happens once, in `atDebug()` or `atLevel()`. After that the default builder calls each supplier as it is added, so if the backend drops the event later, which `LoggingEventAware` permits, the values have already been computed. The supplier only saves the work that the level check rules out.
- Is addArgument(() -> order) any cheaper than addArgument(order) when DEBUG is enabled?No. Both hand the builder a reference it already has; the supplier just adds a lambda. Either way `toString()` runs only when the event is formatted. A supplier pays off only when producing the value is itself costly, such as rendering a large collection into a summary string.
A supplier is like a takeaway order phoned to a shop that may be closed. If the shop is closed (the level is disabled), nobody ever starts cooking. If it is open, the kitchen starts cooking the moment the order is taken, not when you arrive to collect it, so an order you later cancel (an event a backend filter drops) has already been cooked.
- addArgument(Supplier) waits until the message is formatted before calling get().
- On a disabled level, addArgument(expensive()) skips calling expensive().
- The no-op builder calls each Supplier and then discards the result.
- A Supplier is called again each time an appender writes the event.
- Suppliers make side effects inside log statements safe because they are lazy.
Assumes SLF4J 2.0.20 and its default DefaultLoggingEventBuilder; the Supplier overloads are part of the 2.0 fluent API and absent from 1.7.