Sub topic 4
Writing log statements with parameterized messages
This chapter assumes you know basic Java, can run a Spring Boot application, and have read the earlier chapters on SLF4J, Logback and log levels. Here you will write log statements correctly and avoid the usual mistakes.
Getting a Logger
Application code logs through the SLF4J Logger interface. Spring Boot's logging starter wires Logback behind it, so your code never imports a Logback class. Each class creates its own logger, named after the class. The name appears in the log pattern and is what you target when you set levels by package.
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);
}
}The logger is static final, so one instance is shared by all objects of the class. Passing OrderService.class gives the logger the name com.example.orders.OrderService (or whatever your package is).
Placeholders instead of concatenation
The {} marker is a placeholder. SLF4J replaces each one, in order, with the matching argument.
log.debug("Order " + orderId + " has " + items + " items"); // avoid
log.debug("Order {} has {} items", orderId, items); // preferWith concatenation, Java builds the full string before debug is called, even when DEBUG is disabled. With placeholders, SLF4J checks the level first. If DEBUG is off, no message is built. The saving is small for a short message and large inside a loop or a hot path.
Placeholders still evaluate their arguments. If an argument is expensive to compute, guard the call or pass a lambda through the fluent API:
if (log.isDebugEnabled()) {
log.debug("Cart state: {}", buildExpensiveSummary(cart));
}
log.atDebug()
.addArgument(() -> buildExpensiveSummary(cart))
.log("Cart state: {}");The lambda runs only when DEBUG is enabled.
Logging exceptions
Pass the exception as the last argument, after all the values for placeholders. SLF4J detects a trailing Throwable that has no placeholder and prints its stack trace.
log.error("Order {} failed", orderId, ex); // message plus stack trace
log.error("Order {} failed: {}", orderId, ex); // trace is still logged: ex fills no placeholder
log.error("Order failed: " + ex.getMessage()); // loses the stack traceDo not log ex.getMessage() alone. Many exceptions have a null or vague message, and the stack trace shows where the failure happened.
Choosing the level
Pick the level that matches who needs to see the message.
| Level | Typical use in this example |
|---|---|
| `info` | A business event: "Placing order…" |
| `debug` | Detail for developers: "Processing order…" |
| `error` | A failure that needs attention, with the exception |
Common mistakes
- Concatenating strings in the message, which does needless work and makes messages harder to search.
- Supplying the wrong number of arguments. Extra arguments are ignored and missing ones leave a literal
{}in the output. - Logging an exception and then rethrowing it, so the same stack trace appears at every layer.
- Calling
printStackTrace()orSystem.out.println, which bypasses levels, patterns and files.
Exercise
A catch block contains log.error("Payment {} failed: " + ex.getMessage(), paymentId);. Name two problems and give a corrected statement.
Show answer
The statement concatenates a string, so the message is built whatever the level, and it logs only the exception message, so the stack trace is lost. Corrected: log.error("Payment {} failed", paymentId, ex);
Exercise
What does this statement print for the order ID if it is called as shown, and why? log.info("Order {} shipped to {}", orderId);
Show answer
The first {} is replaced with the order ID. The second {} has no argument, so it appears literally in the output as {}. SLF4J does not throw an error for a mismatch.