Sub topic 4
Writing log statements with parameterized messages
This chapter assumes you can write a Spring Boot service class, know what a log level is (covered in the previous chapter), and have SLF4J and Logback on the classpath through spring-boot-starter. It covers how to obtain a Logger, how to write messages efficiently, how to log exceptions, and the mistakes that cause trouble in practice.
Getting a logger
You write log statements against the SLF4J API, not against Logback. In every class that logs, declare one Logger and name it after the class.
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
@Service
public class OrderService {
private static final Logger log = LoggerFactory.getLogger(OrderService.class);
public void placeOrder(String orderId, int items) {
log.info("Placing order {} with {} items", orderId, items);
try {
process(orderId);
} catch (IllegalStateException ex) {
log.error("Order {} failed", orderId, ex);
}
}
private void process(String orderId) {
log.debug("Processing order {}", orderId);
}
}Passing OrderService.class sets the logger name to the fully qualified class name, com.example.orders.OrderService for example. That name matters later. Logger names form a hierarchy based on the dots, so a level set for com.example.orders applies to every class in that package. Naming loggers after classes is what makes per-package level configuration work.
The field is static final so the logger is looked up once per class, not once per instance. Lombok's @Slf4j generates an equivalent field named log. It is optional, and the plain declaration above has no extra dependency.
Parameterized messages
The {} marker is a placeholder. SLF4J replaces each one, in order, with the matching argument.
log.info("Placing order {} with {} items", orderId, items);You could build the same message with concatenation, but you should not:
log.debug("Processing order " + orderId + " with " + items + " items");The difference is when the work happens. With concatenation, Java builds the string before debug is called, even if DEBUG is disabled and the message is thrown away. With placeholders, the logger first checks whether the level is enabled. Only then does it format the message. In production, where DEBUG is usually off, a debug statement costs a level check and little else.
flowchart TD
A[Call log.debug with template and arguments] --> B{Is DEBUG enabled for this logger?}
B -- No --> C[Return immediately, no string is built]
B -- Yes --> D[Replace each placeholder with an argument]
D --> E[Send the event to the appenders]Placeholders also keep the message template constant. A constant template is easier to search for and easier to group in a log aggregator.
Placeholder rules
- The number of
{}markers should match the number of arguments. Extra arguments are ignored. Missing arguments leave a literal{}in the output. - To print a literal
{}, escape it as\{}. - Arguments are converted with
toString(). Arrays are printed element by element. - A
nullargument prints asnull.
Logging exceptions
Pass the exception as the last argument and do not give it a placeholder.
log.error("Order {} failed", orderId, ex);SLF4J recognizes a trailing Throwable that has no matching {} and logs its full stack trace after the message. Two common variations lose information:
log.error("Order failed: " + ex); // no stack trace, only toString()
log.error("Order {} failed: {}", orderId, ex.getMessage()); // no stack traceThe first loses the stack trace. The second does too, and getMessage() can return null, so you log the word null. Use the form that passes ex last.
Do not log and rethrow the same exception at every layer. A single failure then appears many times, once per layer, and it is hard to tell how many real failures occurred. Either handle the exception and log it once, or let it propagate and log it at the boundary that finally handles it, such as a @ControllerAdvice.
Choosing the level in code
The level methods are trace, debug, info, warn, and error. Choose by who needs to see the message and how urgent it is.
| Situation | Method |
|---|---|
| A business event worth recording in normal operation, such as an order placed | `info` |
| Internal detail useful when diagnosing a problem | `debug` |
| Very fine-grained flow, such as entering a loop iteration | `trace` |
| Something unexpected that the application recovered from, such as a retry | `warn` |
| An operation failed and needs attention | `error` |
A useful test for error: would someone reasonably be paged or look at this in a dashboard? If a user typing a wrong password produces an error, your error count becomes noise.
When you still need a level guard
Placeholders avoid string building, but they do not avoid computing the arguments. In this call, expensiveDump() runs every time:
log.debug("State: {}", expensiveDump());The method is called before debug even runs. If the computation is costly, guard it:
if (log.isDebugEnabled()) {
log.debug("State: {}", expensiveDump());
}Alternatively, SLF4J 2 offers a fluent API that takes a supplier, so the work runs only when the level is enabled:
log.atDebug()
.setMessage("State: {}")
.addArgument(() -> expensiveDump())
.log();Cheap arguments such as a local variable or a getter need no guard. Use the guard only when computing the argument is expensive. Spring Boot 3 ships SLF4J 2, so the fluent API is available.
Common mistakes
- Concatenating strings. It defeats lazy formatting and creates a different message text for every call.
- Dropping the stack trace. Log the exception object itself, last.
- Logging sensitive data. Passwords, tokens, card numbers, and personal data should never reach a log. Remember that
toString()on an entity can include fields you did not intend to log. - Logging in a tight loop. Thousands of
infolines per second slow the application and bury useful lines. Log a summary after the loop instead. - Calling
System.out.println. It bypasses levels, patterns, files, and MDC. Use a logger. - Using a shared logger name. Copying
LoggerFactory.getLogger(OtherClass.class)into a new class makes its messages appear to come from the wrong place. - Vague messages.
log.info("Done")tells nobody what finished. Include the identifiers you would need to find the record:log.info("Order {} shipped", orderId).
Verifying the output
With the default console pattern, running placeOrder("A-17", 3) prints a line similar to this:
2026-12-01T10:58:40.270Z INFO 4021 --- [ main] c.example.orders.OrderService : Placing order A-17 with 3 itemsIf the process method throws, the error call prints the message Order A-17 failed followed by the stack trace. The debug line does not appear unless you set logging.level.com.example.orders=debug. The next chapter covers that setting.
Exercise
A teammate writes log.warn("Payment {} declined: {}", paymentId, ex.getMessage()); inside a catch block. Name two problems with this call and show the corrected statement.
Show answer
First, the stack trace is lost, because only the message string is logged. Second, getMessage() may return null, which produces an unhelpful line. Pass the exception as the last argument with no placeholder: log.warn("Payment {} declined", paymentId, ex);.
Exercise
You add log.debug("Cache contents: {}", cache.dumpAll()); and find that requests got slower in production, where DEBUG is off. Why does this happen, and how do you fix it?
Show answer
Placeholders defer only the string formatting. The argument cache.dumpAll() is evaluated before debug is called, so the expensive work runs on every request. Wrap the statement in if (log.isDebugEnabled()), or use the fluent API with a supplier: log.atDebug().setMessage("Cache contents: {}").addArgument(() -> cache.dumpAll()).log();.