Sub topic 11
Logging errors without noise or duplication
This chapter assumes you have a working @RestControllerAdvice like the one from the previous chapters, and that you know SLF4J basics (Logger, log levels). It covers where to log an exception, at which level, and how to avoid logging it twice.
Log where you handle, not where you catch
A global handler is the one place that sees every exception that reaches the client. Logging there gives you a single, predictable record per failed request.
The common mistake is logging at every layer. A repository logs the exception and rethrows it. The service logs it and rethrows it. The handler logs it again. One failure then produces three stack traces, and nobody can tell how many requests actually failed.
package com.example.orders;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
@Service
class OrderService {
private static final Logger log = LoggerFactory.getLogger(OrderService.class);
Order find(long id) {
try {
return load(id);
} catch (IllegalStateException ex) {
// Anti-pattern: logs here, then the handler logs it again
log.error("Could not load order", ex);
throw ex;
}
}
private Order load(long id) {
throw new IllegalStateException("Database unavailable");
}
}Remove the try block. Let the exception propagate, and log it once in the handler. If a lower layer has useful context, wrap the exception with that context instead of logging it:
throw new IllegalStateException("Could not load order " + id, ex);Choose the level by who caused the error
Not every exception deserves an ERROR entry. Use the HTTP status as a guide.
| Situation | Typical status | Level | Stack trace |
|---|---|---|---|
| Unknown id, invalid input | 400, 404, 409 | `DEBUG` or `INFO` | No |
| Repeated abuse, odd client behavior | 4xx | `WARN` | No |
| Bug or failed dependency | 500, 503 | `ERROR` | Yes |
Client errors are normal traffic. A stack trace for every 404 buries the real problems. Server errors need the trace, because it is the only way to find the cause.
@ExceptionHandler(OrderNotFoundException.class)
public ProblemDetail handleOrderNotFound(OrderNotFoundException ex) {
log.debug("Order {} not found", ex.getOrderId());
ProblemDetail problem = ProblemDetail.forStatusAndDetail(HttpStatus.NOT_FOUND, ex.getMessage());
problem.setTitle("Order not found");
problem.setProperty("orderId", ex.getOrderId());
return problem;
}
@ExceptionHandler(Exception.class)
public ProblemDetail handleUnexpected(Exception ex) {
log.error("Unhandled exception", ex);
return ProblemDetail.forStatusAndDetail(
HttpStatus.INTERNAL_SERVER_ERROR, "An unexpected error occurred");
}Pass the exception as the last argument, as in log.error("Unhandled exception", ex). SLF4J then prints the stack trace. Writing log.error("Failed: " + ex.getMessage()) drops the trace and the cause chain.
Keep the log useful and safe
The client gets a generic message, so the log must carry what the client does not. Include identifiers such as the order id or the request path. A correlation id stored in the SLF4J MDC (Mapped Diagnostic Context) lets you match a client report to a log line. Do not log passwords, tokens, or full request bodies.
You can change levels without code edits in application.properties:
logging.level.com.example.orders.ApiExceptionHandler=DEBUGExercise
A service method catches a SQLException, calls log.error with the exception, and rethrows it. A global handler for Exception also calls log.error. What is wrong, and how do you fix it?
Show answer
The same failure is logged twice, so the logs overstate how many errors happened. Remove the catch-and-log in the service. If it has useful context, wrap the exception in a new one with a descriptive message and let it propagate. Log it once in the global handler, at ERROR with the stack trace.