Sub topic 11
Logging errors without noise or duplication
This chapter assumes you can build a Spring Boot REST controller, you know the @RestControllerAdvice pattern from the previous chapters, and you have SLF4J on the classpath (Spring Boot includes it with Logback by default). The goal is a logging policy for exceptions: each failure is logged once, at a level that matches its meaning, with enough context to debug it.
Why error logging needs a policy
Error handling and error logging are separate concerns. The response goes to the client. The log goes to the people who run the service. A handler that returns a 404 body for a missing order does not automatically need a log line, and a handler that returns a 500 body always does.
Without a policy, two problems appear:
- Noise. Every client mistake (a bad id, an invalid body) is logged as an
ERRORwith a stack trace. Real faults are buried, and alerts based on error counts fire for problems that are not yours to fix. - Duplication. The same exception is logged in the service, again in the controller, and again in the advice. One failure produces three stack traces, and nobody can tell whether it happened once or three times.
A useful rule: log an exception where you handle it, not where you pass it along.
Choose the level by who caused the failure
The HTTP status code already tells you whose fault the failure is. Use it to pick the level.
| Failure | Typical status | Level | Stack trace? |
|---|---|---|---|
| Validation failure, malformed JSON | 400 | `DEBUG` or no log | No |
| Resource not found | 404 | `DEBUG` or `INFO` | No |
| Business rule conflict | 409 | `INFO` | No |
| Downstream dependency failed or timed out | 502, 503, 504 | `WARN` | Usually yes |
| Unexpected exception | 500 | `ERROR` | Yes |
The reasoning: 4xx errors are the client's mistakes, and the service worked as designed. They are useful as metrics, but a stack trace adds nothing because the cause is already in the message. 5xx errors mean the service failed. You need the stack trace to find out why, and ERROR is the level an alerting rule should watch.
Log in one place: the advice
The handler class from the earlier chapter is the natural single point for logging. Every exception that leaves a controller passes through it, so it can apply the policy consistently. The code below extends that handler with level-aware logging.
package com.example.orders;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ProblemDetail;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
@RestControllerAdvice
public class LoggingApiExceptionHandler {
private static final Logger log = LoggerFactory.getLogger(LoggingApiExceptionHandler.class);
@ExceptionHandler(OrderNotFoundException.class)
public ProblemDetail handleOrderNotFound(OrderNotFoundException ex) {
// Client error: one line, no stack trace.
log.info("Order lookup failed: orderId={}", 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) {
// Server error: pass the exception as the last argument so the
// stack trace is printed.
log.error("Unhandled exception", ex);
return ProblemDetail.forStatusAndDetail(
HttpStatus.INTERNAL_SERVER_ERROR, "An unexpected error occurred");
}
}Note the two different calls. log.info("... orderId={}", id) uses a placeholder and prints one line. log.error("Unhandled exception", ex) passes the exception as the final argument, and SLF4J prints the full stack trace and the chain of causes.
Do not write log.error("Failed: " + ex.getMessage()). It drops the stack trace, so you lose the location of the failure. It also builds the string even when the level is disabled.
Common mistakes that cause duplicates
Log and rethrow
// Anti-pattern
try {
repository.save(order);
} catch (DataAccessException ex) {
log.error("Could not save order", ex); // logged here...
throw ex; // ...and again in the advice
}The service logs the exception and rethrows it, and then the advice logs it again. Choose one. If the service cannot add anything useful, do not catch the exception. If it can add context, wrap the exception and let the advice log the wrapper once:
try {
repository.save(order);
} catch (DataAccessException ex) {
throw new OrderStorageException(order.id(), ex); // cause is preserved
}Pass the original exception as the cause. The stack trace printed by the advice then includes a Caused by: section with the original failure.
Logging inside every handler method
If each @ExceptionHandler calls log.error(...), a rule change (for example, "404s are no longer logged") means editing many methods. Keep the logging decision in one small helper or one clearly named class.
Swallowing exceptions
An empty catch block or a handler that returns a 500 without logging is the opposite problem. The client sees a failure and the logs show nothing. Every path that produces a 5xx response must log the exception.
Interaction with Spring's own logging
Spring MVC logs some exceptions itself. When a @ExceptionHandler resolves an exception, Spring's ExceptionHandlerExceptionResolver normally logs it only at DEBUG. By contrast, the default DefaultHandlerExceptionResolver writes WARN messages for standard MVC exceptions such as HttpRequestMethodNotSupportedException when no handler of yours takes over. Because of this, the same exception can show up once from Spring and once from your handler.
If you see doubled lines, check the logger names in the output. You can raise the level of Spring's resolver loggers in application.properties:
# Quiet the framework's own resolver messages once your advice logs the failure
logging.level.org.springframework.web.servlet.mvc.method.annotation.ExceptionHandlerExceptionResolver=WARN
logging.level.org.springframework.web.servlet.handler.HandlerMethodExceptionResolver=WARNAdjust the logger names to match what you see in your own output.
Add context with MDC
A stack trace says what failed. It does not say which request. The Mapped Diagnostic Context (MDC) is a per-thread map in SLF4J that Logback can print on every log line. Put a request id into it once, and every line written while handling that request carries the id.
package com.example.orders;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
@Component
public class RequestIdFilter extends OncePerRequestFilter {
private static final String HEADER = "X-Request-Id";
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response,
FilterChain chain) throws ServletException, IOException {
String requestId = request.getHeader(HEADER);
if (requestId == null || requestId.isBlank()) {
requestId = UUID.randomUUID().toString();
}
MDC.put("requestId", requestId);
response.setHeader(HEADER, requestId);
try {
chain.doFilter(request, response);
} finally {
MDC.remove("requestId"); // threads are reused; always clean up
}
}
}Then include the value in the log pattern:
logging.pattern.level=%5p [%X{requestId}]The finally block matters. Servlet containers reuse threads, so a value left in the MDC leaks into the next request on that thread.
Because the response also carries the X-Request-Id header, a client can report that id in a bug report, and you can search the logs for it. Returning the id to the client is safe. Returning the stack trace is not, as the security chapter explains.
Avoid logging sensitive data
Exception messages and request bodies can contain passwords, tokens, card numbers or personal data. Rules that keep logs safe:
- Never log full request bodies in an error handler.
- Log identifiers (
orderId=42) rather than whole objects. - Check what your exception messages include. A message such as
"Invalid token abc123"ends up in the log. - Be careful with
toString()on domain objects, sincelog.info("{}", user)calls it.
Avoid log flooding
A client that sends bad requests in a loop can write thousands of lines per second. Two measures help:
- Keep 4xx handling at
DEBUGorINFOand rely on metrics (such as Micrometer'shttp.server.requestscounters, tagged by status) to see their rate. - For repeated 5xx failures from one dependency, log the first and summarize the rest, using a circuit breaker or a rate-limited logger, so one outage does not fill the disk.
How the pieces fit together
Verifying the behavior
You can check that a failure is logged exactly once with Spring Boot's OutputCaptureExtension, which captures console output in a test.
package com.example.orders;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
import org.springframework.boot.test.system.CapturedOutput;
import org.springframework.boot.test.system.OutputCaptureExtension;
import org.springframework.test.web.servlet.MockMvc;
@WebMvcTest(OrderController.class)
@ExtendWith(OutputCaptureExtension.class)
class OrderLoggingTest {
@Autowired
MockMvc mockMvc;
@Test
void unknownOrderIsLoggedOnceWithoutStackTrace(CapturedOutput output) throws Exception {
mockMvc.perform(get("/orders/99"));
assertThat(output.getOut()).containsOnlyOnce("Order lookup failed: orderId=99");
assertThat(output.getOut()).doesNotContain("OrderNotFoundException:");
}
}This test assumes the handler from this chapter is the only advice registered with @Order priority over the earlier ApiExceptionHandler. If both advice classes are on the classpath, they handle the same exception types, and Spring uses whichever it finds first. Keep one advice class per application, or give each a distinct scope, to avoid confusing results.
Checklist
- Log each exception once, where it is handled.
- Never log and rethrow. Wrap with context instead, and keep the cause.
- Map level to status class: 4xx at
DEBUGorINFO, 5xx atERROR. - Pass the exception object as the last argument to get the stack trace.
- Add a request id through the MDC and return it in a response header.
- Keep secrets and full request bodies out of logs.
- Watch for failures that bypass the advice, such as filter errors.
Exercise
A service method catches a DataAccessException, calls log.error("save failed", ex), and rethrows it. The @RestControllerAdvice also calls log.error("Unhandled exception", ex) for Exception. What happens when a save fails, and how do you fix it?
Show answer
The same failure is logged twice with two stack traces, once in the service and once in the advice, which makes one fault look like two. Remove the log call from the service. If the service has useful context, such as the order id, throw a new exception that wraps the original as its cause, and let the advice log it once at ERROR.
Exercise
Why should the MDC cleanup (MDC.remove) go in a finally block in the request filter?
Show answer
Servlet containers reuse threads from a pool. If the requestId stays in the MDC after the request ends, the next request handled by that thread would log the old id until it is overwritten. A finally block removes the value even when the request throws an exception.