Sub topic 16
Best practices and common pitfalls
This chapter assumes you can write log statements with SLF4J, set levels in application.properties, and use MDC as covered earlier. It collects the habits that keep logs useful, cheap, and safe, and the mistakes that most often undo them.
Log the right things at the right level
Pick the level by who needs to react to the message.
| Level | Use it for |
|---|---|
| ERROR | A failure that needs attention, such as a lost order or a failed payment |
| WARN | An unexpected event the application recovered from, such as a retry |
| INFO | Business milestones, such as startup or an order placed |
| DEBUG | Details for diagnosing a problem in development |
A common error is logging expected conditions as ERROR. A user entering a wrong password is not an application failure. If every bad input triggers an alert, people stop reading alerts.
Use parameterized messages
Use {} placeholders instead of string concatenation. With concatenation, Java builds the string even when the level is disabled. With placeholders, SLF4J formats the message only if the level is enabled.
log.debug("Order {} has {} items", orderId, items); // good
log.debug("Order " + orderId + " has " + items); // builds the string every timeIf an argument is expensive to compute, guard the call or use the fluent API with a lazy supplier.
log.atDebug()
.setMessage("Cart snapshot: {}")
.addArgument(() -> cart.expensiveSummary())
.log();Pass the exception as the last argument
Logging only ex.getMessage() discards the stack trace. Pass the exception object last, after the placeholder values. SLF4J does not use it for a placeholder and prints the stack trace instead.
log.error("Order {} failed", orderId, ex); // message and stack trace
log.error("Order failed: " + ex.getMessage()); // stack trace lostAlso avoid logging and rethrowing the same exception at every layer. One failure then appears as many entries. Log it once, where you handle it.
Keep sensitive data out of logs
Logs are copied to files, aggregators, and support tickets, so they often have wider access than your database. Do not log passwords, tokens, card numbers, or full personal records. Log identifiers such as an order ID instead. Be careful with log.debug("Request: {}", request) when the object's toString() includes every field.
public String mask(String card) {
return "****" + card.substring(card.length() - 4);
}Clean up MDC
Servlet containers reuse threads. If you put a value in MDC and do not remove it, the next request on that thread logs the old value. Always call MDC.remove in a finally block, as the RequestIdFilter did. Values also do not follow work into other threads, so copy the context when you hand work to an executor.
Avoid costly logging in hot paths
Logging inside tight loops can slow an application and fill disks. Log a summary after the loop. Keep root at warn or info in production, and raise a single package to debug temporarily through the Actuator loggers endpoint rather than redeploying.
Common pitfalls at a glance
- Leaving
logging.level.root=debugin production, which also exposes library internals. - Using
System.out.printlnore.printStackTrace(), which bypass levels, patterns, and files. - Writing a file with no rolling limits, so the disk fills.
- Mixing logging backends on the classpath, which causes SLF4J "multiple bindings" warnings.
- Messages without context, such as "Failed", that cannot be traced to a request.
Exercise
A catch block contains log.error("Payment failed for " + id + ": " + ex.getMessage());. Name two problems and give a corrected line.
Show answer
It builds the string by concatenation even when ERROR is disabled, and it drops the stack trace by logging only the message. Corrected: log.error("Payment failed for {}", id, ex);
Exercise
Why must MDC.remove be called in a finally block?
Show answer
Request threads are reused. If the value is not removed, even when an exception occurs, later requests on the same thread log a stale request ID.