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?
answer
- position and type, not anchors
- only the last element is examined
- getThrowableCandidate and trimmedCopy
- a leftover {} stays literal
- a single Throwable picks another overload
basics
~20 sWhen 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().
solid answer
~40 sIn SLF4J 2.0 the rule is positional and type-based. `NormalizedParameters.getThrowableCandidate` looks only at the **last** element of the argument array; if it is `instanceof Throwable`, `trimmedCopy` removes it and it becomes the event's throwable, while the rest fill the anchors. The anchor count plays no part: `log.error("Reserve failed for {} in {}", sku, e)` prints `Reserve failed for SKU-7 in {}` plus the stack trace. With a single exception argument Java picks `error(String, Throwable)`, so that message is not formatted at all. When an inventory service's error line shows only `java.lang.IllegalStateException: no stock` with no trace, the exception sat in an earlier position, as in `log.error("{} failed for {}", e, sku)`, or the code passed `e.getMessage()` or `e.toString()` instead of `e`.
code
java · 13 linesIllegalStateException e = new IllegalStateException("no stock");
log.error("Reserve failed for {} in {}", sku, e);
// Reserve failed for SKU-7 in {} + stack trace of e
log.error("{} failed for {}", e, sku);
// java.lang.IllegalStateException: no stock failed for SKU-7 (no stack trace)
log.error("Lookup failed: {}", e);
// Lookup failed: {} + stack trace of e (error(String, Throwable) was chosen)
log.error("Reserve failed: {}", e.getMessage(), e);
// Reserve failed: no stock + stack trace of ego deeper
Remember the habit: the exception goes last, with no {} for it, and you pass the exception object rather than its message.
Explain the mechanism: only the last array element is checked with instanceof Throwable, trimmedCopy removes it, the anchor count is ignored, and a lone exception reaches error(String, Throwable).
Diagnose a service whose error lines show only toString() by reading the call sites, and know that a leftover literal {} next to a stack trace is harmless while a missing trace loses evidence.
Decide whether to enforce exception placement with a static-analysis rule across services, weighing the false positives against incidents investigated without a stack trace.
## Why the formatter has to decide SLF4J's classic `Logger` methods take a message pattern and a list of arguments, for example `error(String format, Object... arguments)`. Arguments are typed `Object`, so nothing in the method signature says which one, if any, is an exception. Yet an exception should not be printed like a value: the useful output is its **stack trace**, which a backend prints after the message, not its one-line `toString()` (class name plus message) squeezed into the text. SLF4J therefore needs a rule for picking the **throwable** out of the arguments. ## The rule in SLF4J 2.0.20 The rule lives in `org.slf4j.helpers.NormalizedParameters` (new in 2.0) and is reused by `MessageFormatter.arrayFormat` and by the `AbstractLogger` base class that `slf4j-simple`, `slf4j-jdk14` and `slf4j-reload4j` extend: 1. `getThrowableCandidate(argArray)` looks at the **last element only**. If it is `instanceof Throwable` it is the candidate; otherwise there is none. 2. If there is a candidate, `trimmedCopy(argArray)` builds a new array **without the last element**. 3. The trimmed array fills the `{}` anchors and the candidate travels with the event as its throwable. The **anchor count is never consulted**. SLF4J's own test formats `"{}{}{}{}"` with `1, 2, 3` and a trailing `Throwable` and expects `123{}` with the throwable extracted: the fourth anchor stays literal rather than receiving the exception. Older material sometimes adds a condition that the exception counts only if no anchor is left for it; the 2.0.20 code has no such condition. ## How each call shape reaches the rule | Call | What happens in SLF4J 2.0.20 | |---|---| | `error("Lookup failed: {}", e)` with `e` typed as an exception | Java picks `error(String, Throwable)`; the message is used unformatted, so `{}` prints literally, and `e` is the cause | | `error("Failed {}", sku, e)` | `AbstractLogger`'s two-argument path checks whether the second argument is a `Throwable`; it is, so `sku` fills the anchor and `e` is the cause | | `error("Reserve {} of {} for {}: {}", qty, sku, order, e)` | varargs path: last element is a `Throwable`, so it is trimmed; the last anchor prints `{}` | | `error("{} failed for {}", e, sku)` | last element is `sku`, not a `Throwable`; `e` is an ordinary value printed by `toString()`, no stack trace | When a provider receives an explicit throwable, `NormalizedParameters.normalize` returns it as is and leaves the argument array untouched; extraction runs only when no throwable was supplied. ## Why the inventory service prints toString() An inventory service whose error lines *sometimes* show `java.lang.IllegalStateException: no stock` and no trace is almost always hitting one of these: - **The exception is not last.** `log.error("{} failed for {}", e, sku)` renders `e` into the first anchor. Only the final position is examined. - **A string was passed instead of the exception.** `e.getMessage()` or `e.toString()` is a `String`, so it is never a candidate; `"Failed: " + e` concatenates the `toString()` into the pattern. - **The exception is wrapped in another value.** An exception inside a list or a result object is printed through that object's `toString()`. The word *sometimes* usually points at several call sites written differently, not at nondeterminism: the rule is a pure function of the argument array. ## Reading a suspicious line back to its call site 1. **Find the logger name and message text** in the line and search the code for the pattern string. 2. **Count the arguments and note which position the exception occupies.** If it is not last, that is the defect. 3. **Check the type actually passed.** A `String` built from the exception, or an object that merely holds one, is never extracted. 4. **Look for a leftover literal `{}`** next to a stack trace: that is the harmless sign of an anchor written for the exception, and the anchor can simply be deleted. ## Habits that keep stack traces - Put the exception **last and give it no anchor**: `log.error("Reserve failed for {} in {}", sku, warehouse, e)`. - Want the exception's message in the text as well? Pass it as a value and the exception last: `log.error("Reserve failed: {}", e.getMessage(), e)`. - Never rely on a `{}` to show an exception; at best it prints a literal `{}`, at worst the one-line `toString()`. - How the stack trace is laid out after the message is the backend's job, not SLF4J's.
- Why does `log.error("Lookup failed: {}", e)` print a literal `{}` when `e` is an exception?Java overload resolution prefers `error(String, Throwable)` over `error(String, Object)` because `Throwable` is the more specific type. That method treats its first argument as a plain message, not a pattern, so nothing fills the `{}`. The exception is still logged as the cause with its stack trace.
- How do you get both the exception's message into the text and its stack trace?Pass the message as an ordinary argument and the exception last: `log.error("Reserve failed: {}", e.getMessage(), e)`. The two-argument path sees that the second argument is a `Throwable`, removes it as the cause, and fills the anchor with the message string.
- How would you stop misplaced exceptions from recurring across a large codebase?Add a static-analysis or review rule that flags a `Throwable` passed in any position but the last, and `getMessage()` or string concatenation of an exception in a log call. A test that logs through a capturing provider and asserts the event carries a throwable also catches regressions on critical paths.
A mail clerk who always checks the last item in an envelope: if it is an incident report, it goes into the incident file, however many blanks the letter left for it. An incident report tucked earlier in the envelope is simply read out as part of the letter.
- The exception becomes the cause only if no {} anchor is left for it.
- SLF4J finds a Throwable anywhere in the arguments and prints its stack trace.
- Giving the exception its own {} prints the stack trace inline in the message.
- Passing e.getMessage() as the last argument still produces a stack trace.
- Which argument is the cause varies between runs, so the output is nondeterministic.
Assumes SLF4J 2.0.x, checked against 2.0.20, where NormalizedParameters (added in 2.0) and MessageFormatter define the trailing-throwable rule; verify a 1.x formatter's behaviour separately rather than assuming it matches.