Sub topic 11
The Fluent API and Key-Value Pairs
This chapter assumes that you know basic Java, can add Maven or Gradle dependencies, and understand the SLF4J Logger API. It focuses on SLF4J 2.x, whose fluent API makes structured logging easier.
Why use the fluent API?
Traditional SLF4J calls put values into a message template:
log.info("Order {} changed to {}", orderId, status);This is useful for readable text, but the values are part of the message. A log collector cannot always treat orderId and status as separate searchable fields.
The fluent API attaches named key-value pairs to the log event:
log.atInfo()
.addKeyValue("orderId", orderId)
.addKeyValue("status", status)
.log("Order status changed");Here, orderId=42 and status=SHIPPED are event fields. A compatible backend or encoder can render them as structured data.
Building a fluent log event
The atInfo() method selects the level and returns a log event builder. You can then add fields, an exception, and the final message.
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class OrderService {
private static final Logger log =
LoggerFactory.getLogger(OrderService.class);
public void changeStatus(long orderId, String status) {
log.atInfo()
.addKeyValue("orderId", orderId)
.addKeyValue("status", status)
.log("Order status changed");
}
public static void main(String[] args) {
new OrderService().changeStatus(42, "SHIPPED");
}
}The terminal log(...) call writes the event. Without it, the builder only describes a possible event. The fluent API also provides methods such as atTrace(), atDebug(), atWarn(), and atError().
You can add an exception with setCause:
try {
chargeCustomer();
} catch (RuntimeException e) {
log.atError()
.addKeyValue("customerId", customerId)
.setCause(e)
.log("Payment failed");
}The exception remains separate from the message, so the backend can print its type and stack trace correctly.
Lazy values and disabled levels
A fluent builder does not automatically make every calculation cheap. If creating a value is expensive, use a Supplier overload:
log.atDebug()
.addKeyValue("diagnostics", () -> buildDiagnostics())
.log("Debug state");The supplier can be evaluated only when debug logging is enabled. This avoids work for a disabled level.
| Operation | Purpose |
|---|---|
| `atInfo()` | Selects the event level |
| `addKeyValue("name", value)` | Adds a named field |
| `setCause(exception)` | Attaches an exception and stack trace |
| `log("message")` | Emits the completed event |
How fields reach the output
The SLF4J API creates the event, but a provider and backend decide how it is written. Some configurations print key-value pairs in plain text. Others encode them as JSON.
Adding a key-value pair does not guarantee that every backend will display it. Check the provider and encoder configuration when fields are missing.
Practical choices
Use the fluent API when a value should be queried independently from the human-readable message. Keep the message useful for a person reading the event. Do not place passwords, access tokens, payment details, or full personal records in fields. Structured output makes sensitive data easier to collect and copy.
Prefer identifiers and measurements over large objects:
log.atInfo()
.addKeyValue("orderId", orderId)
.addKeyValue("itemCount", itemCount)
.addKeyValue("durationMs", durationMs)
.log("Order completed");A field name is part of your logging interface. Changing orderId to id can break searches and alerts, so choose names deliberately.
Exercise
Why should orderId be added with addKeyValue instead of inserted only into the message text?
Show answer
A named field can be rendered and searched independently by a structured logging backend, while a value inside message text is harder to query reliably.