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?
answer
- what the builder checks at log()
- event-aware or not
- markers, then pairs, then message
- first marker only on one path
- arriving is not being written
basics
~20 sDefaultLoggingEventBuilder 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.
solid answer
~40 sAt `log()`, the default builder checks the bound `Logger`. If it implements `LoggingEventAware`, it gets the `LoggingEvent` intact, with `getKeyValuePairs()` and `getMarkers()`, and the backend's output format decides whether they become fields. If it implements `LocationAwareLogger`, or only plain `Logger`, SLF4J merges everything into the message string, each marker, then each pair as `key=value`, then the message, passing just the first marker as an object on the location-aware path and none on the plain one. So `slf4j-simple` and `slf4j-jdk14` print the prefix. Event-awareness alone guarantees nothing: the `slf4j-reload4j` adapter is event-aware but builds its Log4j 1 event from message and arguments only, so the pairs disappear. Diagnose by finding the bound provider and checking whether its logger implements `LoggingEventAware`.
code
java · 4 linesLogger logger = LoggerFactory.getLogger(PaymentService.class);
boolean eventAware = logger instanceof org.slf4j.spi.LoggingEventAware;
System.err.println(LoggerFactory.getILoggerFactory().getClass().getName()
+ " eventAware=" + eventAware);go deeper
Recall that pairs are added with addKeyValue() and that how they appear in the output depends on which backend SLF4J is bound to.
Explain the three branches in DefaultLoggingEventBuilder: an event-aware logger gets the event, while location-aware and plain loggers get markers and key=value text prefixed to the message.
Diagnose from the symptom: find the bound provider, check whether its logger is LoggingEventAware, and know that an event-aware adapter such as slf4j-reload4j can still drop the pairs.
Treat key-value pairs as a contract between code and backend: standardise on a provider that writes them as fields, and assert on a field in an integration test before teams build dashboards on them.
## The symptom A payments team adopts structured logging. They replace `logger.info("Payment captured for order {}", orderId)` with: ```java logger.atInfo() .addKeyValue("orderId", orderId) .addKeyValue("amount", amount) .log("Payment captured"); ``` On one service the line reads `orderId=42 amount=19.99 Payment captured` as plain text; on another the same call produces a record with `orderId` and `amount` as separate fields. The code is identical. What differs is the logger the API is bound to, because the fluent builder decides at `log()` **how to hand the event over**. ## How DefaultLoggingEventBuilder dispatches When `log()` runs, the default builder looks at the bound `Logger` and takes the first branch that fits: 1. **The logger implements `org.slf4j.spi.LoggingEventAware`.** The builder calls its `log(LoggingEvent)` and passes the event intact. The receiver can read `getMessage()`, `getArgumentArray()`, `getKeyValuePairs()`, `getMarkers()` and `getThrowable()` separately. 2. **The logger implements `org.slf4j.spi.LocationAwareLogger`.** The builder merges markers and pairs into the message text and calls the six-argument `log(Marker, String, int, String, Object[], Throwable)`, passing only the **first** marker as an object. 3. **Any other `Logger`.** The builder merges the same way and calls the classic method for the level, such as `info(String, Object...)`, with the cause appended after the arguments. No marker object reaches the logger at all. The order matters: a logger that implements both interfaces, as `Reload4jLoggerAdapter` does, takes the event-aware branch, and the location-aware branch is never tried. ## What the merged text looks like The private method `mergeMarkersAndKeyValuePairsAndMessage` builds the prefix in a fixed order: - each marker's `toString()`, followed by a space; - each pair as `key=value` and a space, the value rendered with `toString()` and no quotes (unlike `KeyValuePair.toString()`, which quotes it); - then the message pattern. A null value is written as `null`, and a value whose `toString()` throws is written as `[FAILED toString()]` instead of aborting the call. Because the prefix becomes part of the **message pattern** on these two paths, a value that itself contains `{}` can capture an argument meant for the message, one more sign that flattened pairs are text, not structure. ## Which providers do what | Logger the event reaches | Interface the builder sees | What happens to pairs and markers | |---|---|---| | `slf4j-simple` (`SimpleLogger`) | neither | merged into the text; no marker object | | `slf4j-jdk14` (`JDK14LoggerAdapter`) | `LocationAwareLogger` | merged into the text; first marker passed | | `slf4j-reload4j` (`Reload4jLoggerAdapter`) | `LoggingEventAware`, checked first | not written: the event is built from message and arguments only | | a backend that implements `LoggingEventAware` and writes pairs | `LoggingEventAware` | delivered as data; its output format decides | The reload4j row is the trap in the other direction: being event-aware means the pairs **arrive**, not that they are **written**. That adapter formats the message with the arguments and creates a Log4j 1 event without any properties, so pairs and markers vanish instead of being prefixed. How a given backend renders `getKeyValuePairs()` as fields is a property of that backend and its encoder, covered with that backend. ## How to diagnose it - **Find the bound provider.** Setting the system property `slf4j.internal.verbosity` to `DEBUG` makes `LoggerFactory` report `Connected with provider of type [...]`; `LoggerFactory.getILoggerFactory().getClass()` gives the same answer at runtime. - **Check the logger class.** `logger instanceof LoggingEventAware` tells you which branch the builder takes. - **Read the output as evidence.** Marker names and `key=value` pairs in front of every fluent message are the fingerprint of the merge branches. - If it is not event-aware, the `key=value` prefix is the expected output, not a bug in your calls. - If it is event-aware and the pairs still do not appear, the backend received them and its output format ignores them; the fix lives in the backend's configuration. ## What to take from it - Key-value pairs are only as structured as the bound backend makes them, so agree on the provider before adopting `addKeyValue` as the structured-logging mechanism. - Cover one representative log line with an integration test against the real provider and assert on the field, not just on the text. - Never parse the merged `key=value` prefix downstream as if it were a contract; it is produced by a private fallback method, not a documented format.
- Why might markers added with addMarker() never trigger a backend's marker-based filter on some providers?Only the event-aware branch hands all markers over as objects. On a `LocationAwareLogger` the builder passes just the first marker; on a plain `Logger` it passes none and only prints each marker's name in front of the message. A filter matching the second marker, or any marker on a plain logger, never sees a `Marker` object. Check the provider before routing on markers, and put the routing marker first.
- On the fallback path, what is written when a pair's value is null or its toString() throws?A null value is written as `key=null`. If `toString()` throws, including a `StackOverflowError` from a cyclic object, the builder catches it, reports it through SLF4J's internal `Reporter` and writes `key=[FAILED toString()]`, so the log call still completes. The merge renders the value itself; it does not use `KeyValuePair.toString()`, which would add quotes.
- The bound logger implements LoggingEventAware, yet the pairs never appear in the output. Where do you look?At the backend, not at SLF4J. The builder delivered the event with `getKeyValuePairs()` intact; the receiving adapter or its output format decides what to write. SLF4J's own reload4j adapter is an example that drops them, since it builds its Log4j 1 event from message and arguments only. Check how that backend renders pairs and configure its output there.
- addKeyValue always produces separate fields, whatever provider is bound.
- The key=value prefix means the application called addKeyValue the wrong way.
- Any provider whose logger is LoggingEventAware is guaranteed to write the pairs.
- Every marker added with addMarker reaches the backend as a Marker object.
- The slf4j-api jar decides the field or JSON format of key-value pairs.
Assumes SLF4J 2.0.20; LoggingEventAware and the merge fallback in DefaultLoggingEventBuilder belong to the 2.0 fluent API, which 1.7 lacks.