Sub topic 16
Best practices and common pitfalls
This chapter assumes you can write SLF4J log statements, set levels in application.properties, and have seen MDC and Actuator. It collects the habits that keep logs useful, cheap, and safe, and the mistakes that most often undo them.
Pick levels for the reader, not the writer
A level is a promise about who needs to see the message and when. Use the levels consistently across the codebase.
| Level | Use it for | Example |
|---|---|---|
| ERROR | An operation failed and someone may need to act | Payment gateway rejected a charge unexpectedly |
| WARN | Something unexpected happened, but the request still succeeded | Fallback cache used after a timeout |
| INFO | Business events and lifecycle milestones, a few per request at most | Order placed, job finished |
| DEBUG | Detail for diagnosing a problem in one component | Computed discount, chosen route |
| TRACE | Very fine detail, such as per-item loops | Each row mapped |
Two mistakes recur. The first is logging expected user errors, such as a failed validation or a "not found" lookup, at ERROR. This floods alerts and teaches the team to ignore them. The second is leaving the root level at debug in production, which multiplies log volume and can expose data. Prefer logging.level.root=warn or info, and raise only the packages you need.
Write statements that are cheap and complete
Always use {} placeholders. With log.debug("Order " + id + " has " + items), Java builds the string even when DEBUG is off. With log.debug("Order {} has {}", id, items), SLF4J formats the message only if the level is enabled.
Placeholders do not help when computing an argument is itself expensive, because Java evaluates the argument before the call. SLF4J 2, which Spring Boot 3 uses, has a fluent API that takes a supplier. The supplier runs only when the level is enabled.
Pass the exception as the last argument, without a placeholder for it. SLF4J then prints the stack trace. Logging only ex.getMessage() loses the stack and the cause chain.
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
@Service
public class PaymentService {
private static final Logger log = LoggerFactory.getLogger(PaymentService.class);
public void charge(String orderId, String cardNumber, long cents) {
log.info("Charging order {} for {} cents, card ending {}",
orderId, cents, last4(cardNumber));
log.atDebug()
.addArgument(() -> describeRouting(orderId))
.log("Routing decision: {}");
try {
callGateway(orderId, cents);
} catch (IllegalStateException ex) {
// Wrap and rethrow. Do not log here as well.
throw new PaymentFailedException("Payment failed for order " + orderId, ex);
}
}
private String last4(String cardNumber) {
return cardNumber.length() <= 4
? "****"
: cardNumber.substring(cardNumber.length() - 4);
}
private String describeRouting(String orderId) {
return "gateway-a for " + orderId;
}
private void callGateway(String orderId, long cents) {
// Call the payment gateway here.
}
public static class PaymentFailedException extends RuntimeException {
public PaymentFailedException(String message, Throwable cause) {
super(message, cause);
}
}
}The card number is never logged in full, and the gateway failure is wrapped with its cause so a single handler higher up can log it once.
Log each failure once
The most common cause of noisy logs is the catch, log, rethrow pattern. Each layer logs the same exception, so one failure produces five stack traces and the count of errors looks five times worse than it is. Pick one place to log, usually a @ControllerAdvice or the outermost boundary of a job or message listener. Inner layers either handle the exception completely or wrap it and let it propagate.
Handle it where you can decide something. If you catch an exception and carry on, log it there at WARN or ERROR with the stack trace. Never swallow it with an empty catch block.
Keep sensitive data out of logs
Logs are copied to aggregators, shared with support staff, and retained for months. Treat them as less protected than the database.
- Never log passwords, tokens, API keys, session IDs, full card numbers, or national ID numbers.
- Avoid logging whole request or response bodies and whole entity objects. A generated
toString()can include every field, including secrets. - Log identifiers, such as an order ID, instead of personal details such as an email address, when an identifier is enough.
- Mask what must appear, as
last4does above. - Be careful with
logging.level.org.springframework.web=debugand HTTP client debug logging. They can print headers and payloads, includingAuthorizationheaders.
A related risk is log injection. If you log user input that contains a newline, an attacker can forge a line that looks like a separate log entry. Strip line breaks from untrusted values, or use structured JSON output, which escapes them.
public final class LogSanitizer {
private LogSanitizer() {
}
public static String clean(String value) {
return value == null ? null : value.replaceAll("[\\r\\n]", "_");
}
}Handle MDC with care
MDC (mapped diagnostic context) values live in a thread-local map. This causes two pitfalls.
- Servlet containers reuse threads. If a filter puts a value in the MDC and does not remove it in a
finallyblock, the next request on that thread logs the old request ID. TheRequestIdFilterfrom the MDC chapter removes the key infinallyfor this reason. - Work handed to another thread does not carry the MDC. Code run through
@Async, an executor, orCompletableFuturelogs with an empty%X{requestId}.
For the second case, copy the context in a TaskDecorator. Spring Boot applies a TaskDecorator bean to its auto-configured task executor. Executors you create yourself need the decorator set explicitly.
import java.util.Map;
import org.slf4j.MDC;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.TaskDecorator;
@Configuration
public class MdcTaskConfig {
@Bean
public TaskDecorator mdcTaskDecorator() {
return runnable -> {
Map<String, String> context = MDC.getCopyOfContextMap();
return () -> {
if (context != null) {
MDC.setContextMap(context);
}
try {
runnable.run();
} finally {
MDC.clear();
}
};
};
}
}Control volume and cost
Logging is I/O, and it can become the slowest part of a hot path.
- Do not log inside tight loops. Log a summary after the loop, such as "Imported 12,000 rows, 3 skipped".
- Do not log every successful health check or poll. At INFO they bury the events you care about.
- Always roll file output. A file without
max-file-sizeandmax-historyeventually fills the disk, which can take the whole host down. Also setlogging.logback.rollingpolicy.total-size-capif disk space is limited. - In containers, prefer writing to the console and let the platform collect it. Files inside a container are lost when it is replaced.
- In production, prefer structured output (
logging.structured.format.console=ecson Spring Boot 3.4 and later) so aggregators can filter by field without parsing text.
Common pitfalls at a glance
| Pitfall | Why it hurts | Fix |
|---|---|---|
| `System.out.println` or `e.printStackTrace()` | No level, no timestamp, bypasses files and filters | Use a `Logger` and pass the exception as the last argument |
| String concatenation in messages | Builds strings even when the level is off | Use `{}` placeholders |
| Catch, log, rethrow at every layer | Duplicate stack traces and inflated error counts | Log once at the boundary |
| Root level left at `debug` | Large volume, possible data exposure | Set the root to `warn` or `info` and raise specific packages |
| MDC not cleared | Stale IDs on reused threads | Remove in `finally` |
| MDC missing in async code | Lines cannot be correlated | Copy the context with a `TaskDecorator` |
| `loggers` endpoint exposed without protection | Anyone can raise levels or read logger config | Secure Actuator and expose only the endpoints you need |
| Unrolled log file | Disk fills | Set size and history limits |
| Raw user input in messages | Forged log lines | Strip line breaks or use JSON output |
Runtime changes through the loggers endpoint are useful for debugging, but they are temporary. Reset the level to null (inherit) or restart when you finish, so a forgotten DEBUG setting does not stay on for weeks.
Exercise
A request handler calls OrderService, which calls PaymentService. Each layer has catch (Exception e) { log.error("Failed: " + e.getMessage()); throw e; }. List the problems with this code and show how to fix the logging.
Show answer
There are four problems. (1) The same failure is logged at every layer, so one error produces several entries. (2) Only e.getMessage() is logged, so the stack trace and cause are lost. (3) String concatenation builds the message even if ERROR is disabled, and the message has no context such as the order ID. (4) The message "Failed" does not say what failed. The fix is to remove the catch and log blocks from the inner layers, or wrap the exception with context, as in throw new PaymentFailedException("Payment failed for order " + orderId, ex). Then log it once at the boundary, for example in a @ControllerAdvice, with log.error("Request failed for order {}", orderId, ex), where ex is the last argument so the full stack trace is printed.
Exercise
After deploying, you notice that log lines from an @Async method show an empty [%X{requestId}], and that some lines from normal requests show the ID of a previous request. Name the cause of each symptom and the fix.
Show answer
The empty ID in @Async code happens because the MDC is thread-local and the async task runs on another thread, so the map is not copied. Fix it with a TaskDecorator that copies MDC.getCopyOfContextMap() into the worker thread and clears it afterwards. The stale IDs happen because the servlet thread was reused and the filter did not remove the key. Fix it by calling MDC.remove("requestId") in a finally block around chain.doFilter.