Sub topic 11
The fluent API and key-value pairs
This chapter assumes you can write SLF4J statements with {} placeholders, that you know the log levels, and that you have Logback configured through logback.xml. You should also know what MDC does. Everything here needs SLF4J 2.0 or later on the classpath. The examples use slf4j-api 2.0.16 and logback-classic 1.5.12.
What the fluent API adds
The classic SLF4J call is a single method such as log.info("Charging customer {}", id). The message and its arguments are all you can pass. Anything else you want to record, such as an order ID, a status or a duration, has to be written into the message text. Later, someone who wants to search logs by order ID must parse that text.
SLF4J 2.0 adds a fluent API. You start from atInfo(), atDebug() and the other at...() methods on the logger. Each one returns a LoggingEventBuilder, and you chain calls on it until you finish with log(). The builder can carry a message, arguments, an exception, markers and key-value pairs. A key-value pair is a named piece of data attached to one log event, kept separate from the message text.
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class FluentExample {
private static final Logger log = LoggerFactory.getLogger(FluentExample.class);
public static void main(String[] args) {
log.atInfo()
.addKeyValue("orderId", 42)
.addKeyValue("status", "SHIPPED")
.log("Order status changed");
}
}The message stays constant ("Order status changed"). The variable parts travel as fields. A backend can print them next to the message, write them as JSON fields or index them.
The method atInfo() is the fluent counterpart of info(). The full set is atTrace(), atDebug(), atInfo(), atWarn() and atError(). There is also atLevel(Level), which takes a level chosen at run time.
How a fluent call is processed
The builder collects the parts of the event. Nothing is sent to the backend until you call one of the log(...) methods. The backend then receives a single event that holds all the parts.
If the level is disabled, atDebug() returns a no-operation builder. Calls such as addKeyValue on it do nothing, and log() does nothing. You do not need an isDebugEnabled() guard around the chain. Java still evaluates the arguments you pass, though. addKeyValue("total", computeTotal()) calls computeTotal() even when the event is dropped. The next section covers the supplier overloads that avoid this.
Builder methods
| Method | Purpose |
|---|---|
| `setMessage(String)` | Sets the message template, which may contain `{}` placeholders. |
| `setMessage(Supplier<String>)` | Builds the message only if the level is enabled. |
| `addArgument(Object)` | Supplies the next `{}` value. |
| `addArgument(Supplier<?>)` | Supplies the next `{}` value lazily. |
| `addKeyValue(String, Object)` | Attaches a named field to the event. |
| `addKeyValue(String, Supplier<Object>)` | Attaches a named field computed lazily. |
| `setCause(Throwable)` | Attaches an exception and its stack trace. |
| `addMarker(Marker)` | Tags the event with a marker. |
| `log()`, `log(String)`, `log(Supplier<String>)` | Ends the chain and emits the event. |
The log(String) overloads, including log(String, Object) and log(String, Object...), set the message and arguments and emit in one step. So log.atInfo().log("Order {} shipped", id) works the same as the classic call.
Lazy values
Use the supplier forms for values that are expensive to compute.
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class LazyExample {
private static final Logger log = LoggerFactory.getLogger(LazyExample.class);
public static void main(String[] args) {
List<String> items = List.of("a", "b", "c");
log.atDebug()
.setMessage("Cart contents: {}")
.addArgument(() -> String.join(",", items))
.addKeyValue("itemCount", () -> items.size())
.log();
}
}With the root level at INFO, neither lambda runs, because the builder returned by atDebug() ignores them.
Exceptions
Attach an exception with setCause. This is the fluent form of passing a Throwable as the last argument.
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class CauseExample {
private static final Logger log = LoggerFactory.getLogger(CauseExample.class);
public static void main(String[] args) {
try {
Integer.parseInt("not a number");
} catch (NumberFormatException e) {
log.atError()
.addKeyValue("input", "not a number")
.setCause(e)
.log("Could not parse quantity");
}
}
}The stack trace is printed by the backend's layout, exactly as with log.error("...", e).
Making key-value pairs visible
Adding a key-value pair does not make it appear in your output. The backend's encoder decides what to print. A Logback pattern that only contains %msg drops the pairs. Add the %kvp conversion word, available in Logback 1.3 and later, to print them after the message:
<configuration>
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} %-5level %logger{20} - %msg %kvp%n</pattern>
</encoder>
</appender>
<root level="INFO">
<appender-ref ref="CONSOLE"/>
</root>
</configuration>With this file, FluentExample prints a line like this:
10:15:30.123 INFO FluentExample - Order status changed orderId=42 status="SHIPPED"Logback writes each pair as key=value, and it typically puts string values in double quotes. The exact format can change between versions, so do not write parsers against it. If you need machine-readable output, use a JSON encoder. Logback 1.5 ships ch.qos.logback.classic.encoder.JsonEncoder, which writes each event as a JSON object and includes the pairs in a separate keyValuePairs section. The logstash-logback-encoder library is a common alternative that places the fields at the top level of the JSON.
Two other behaviors matter when you move between backends:
- A backend that does not understand key-value pairs ignores them. Check that your provider supports them before relying on the fields.
- If the backend does not accept full event objects (for example, an old SLF4J 1.7 binding), SLF4J falls back to the plain logger methods. In that case it prepends the pairs to the message text, so you still see them, but not as separate fields.
Key-value pairs, MDC and arguments compared
Three features can carry the same fact, so you need a rule for choosing between them.
| Feature | Scope | Use it for |
|---|---|---|
| Message argument (`{}`) | One event, part of the sentence | Values a human needs inside the message text |
| Key-value pair | One event, separate field | Data about this event that you want to filter or index, such as `orderId` or `durationMs` |
| MDC | Every event on the current thread until removed | Data shared by many lines, such as `requestId` or `userId` |
They combine well. A request handler puts requestId in MDC at the start of the request. Each individual log call then adds its own key-value pairs for the event-specific data:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.slf4j.MDC;
public class CheckoutHandler {
private static final Logger log = LoggerFactory.getLogger(CheckoutHandler.class);
public void handle(String requestId, long orderId, long totalCents) {
try (MDC.MDCCloseable ignored = MDC.putCloseable("requestId", requestId)) {
log.atInfo()
.addKeyValue("orderId", orderId)
.addKeyValue("totalCents", totalCents)
.log("Checkout completed");
}
}
}A pattern with %X{requestId} and %kvp prints both kinds of context on the same line. The request ID comes from the thread. The order fields come from the event.
Common mistakes
- Forgetting
log(). The event is never emitted, and the compiler cannot warn you. - Putting the value in both places. Writing
addKeyValue("orderId", id).log("Order " + id + " shipped")repeats the data. Keep the message constant and let the field carry the value. - Inconsistent key names.
orderIdin one class andorder_idin another makes a search miss half the events. Pick one naming style and use constants for shared keys. - Logging sensitive data as a field. Fields are easier to index and ship than text, so a password or token stored in one spreads further. Never add secrets, full card numbers or access tokens.
- Assuming
System.Loggercan do this.System.Loggerhas no fluent API and no key-value pairs. If you route it into SLF4J with the bridge from the previous chapter, only the formatted message arrives. - Expensive arguments. As noted earlier,
addKeyValue("x", compute())runscompute()whether or not the level is enabled. Use a supplier.
Exercises
Exercise
A teammate writes log.atWarn().addKeyValue("retries", 3).setCause(e); in a catch block, and nothing appears in the log even though WARN is enabled. What is wrong, and what is the fix?
Show answer
The chain never ends with a log(...) call, so no event is emitted. Add .log("Request failed after retries") (or .log() after setMessage) at the end of the chain.
Exercise
Your Logback pattern is %d %-5level %logger - %msg%n. A call log.atInfo().addKeyValue("orderId", 42).log("Shipped") prints only Shipped as its message. Which change makes orderId=42 appear, and when would you use a different encoder instead?
Show answer
Add %kvp to the pattern, for example %d %-5level %logger - %msg %kvp%n, which needs Logback 1.3 or later. Use a JSON encoder, such as Logback's JsonEncoder or the logstash-logback-encoder, when a log platform needs to parse the fields instead of reading text.
Exercise
A request handler sets requestId in MDC, and one log call inside it records the number of rows an import changed. Which feature should carry each value, and why?
Show answer
Use MDC for requestId, because it applies to every line logged on that thread during the request. Use a key-value pair, such as addKeyValue("rowsChanged", n), for the row count, because it describes only that one event.