How to Debug Spring Boot Controllers: Logging, Timing, and 404 Handling
This guide shows how to enable detailed request/response logging, measure controller execution time, and customize 404 error responses in Spring Boot 3.2.5, providing practical code snippets and configuration tips for effective backend debugging and monitoring.
1. Controller Interface Debugging
Logging request parameters, headers, and responses is essential for troubleshooting, security auditing, and monitoring. In most cases, detailed logs help quickly locate errors or verify backend logic.
Problem Diagnosis: View request data to pinpoint incorrect or missing parameters and verify response correctness.
Security Auditing: Record detailed information to trace sensitive data flow and detect potential vulnerabilities.
Monitoring & Alerts: Integrate logs with monitoring systems to trigger alerts on abnormal behavior.
In a Spring Boot project, set the logging level to TRACE for the web package:
logging:
level:
web: TRACEExample controller:
@GetMapping("/index")
public Object index(Long id, String kw) {
HttpHeaders headers = new HttpHeaders();
headers.add("x-version", "1.0.0");
ResponseEntity<Object> response = new ResponseEntity<>(
String.format("【id = %d, kw = %s】", id, kw),
headers,
HttpStatusCode.valueOf(200));
return response;
}After enabling log-request-details: true, the logs include full request and response details, which is invaluable for debugging (not recommended for production).
spring:
mvc:
log-request-details: true2. Measuring Interface Duration
Tracking request processing time aids performance monitoring and fault diagnosis. Common approaches include AOP, interceptors, and external monitoring tools, each with pros and cons.
AOP – Advantages: decoupled code, reusable, easy maintenance. Disadvantages: added complexity, slight performance overhead. Interceptor – Advantages: simple integration with Spring MVC. Disadvantages: limited to web layer. Performance Monitoring Tools – Advantages: comprehensive features, strong visualization. Disadvantages: external dependencies, higher cost.
The article demonstrates a lightweight Spring‑provided solution using ServletRequestHandledEvent:
@Component
public class TimeCountListener implements ApplicationListener<ServletRequestHandledEvent> {
@Override
public void onApplicationEvent(ServletRequestHandledEvent event) {
Throwable failureCause = event.getFailureCause();
if (failureCause != null) {
System.err.printf("错误原因: %s%n", failureCause.getMessage());
}
System.err.println("========================================");
System.err.printf(
"请求客户端地址:%s
请求URL: %s
请求Method: %s
请求耗时: %d毫秒%n",
event.getClientAddress(),
event.getRequestUrl(),
event.getMethod(),
event.getProcessingTimeMillis()
);
System.err.println("========================================");
}
}Testing the same /index endpoint shows accurate timing information:
3. Handling Unpleasant 404 Errors
When a request targets a non‑existent endpoint, Spring Boot returns an error page whose format depends on the Accept header. To unify the response format, replace the default DefaultHandlerExceptionResolver.
Configuration (Spring Boot 3.x):
# Throw exception when no handler is found (will be removed in 3.4)
spring.mvc.throw-exception-if-no-handler-found
# Disable static resource mapping
spring.web.resources.add-mappingsAdjust static resource pattern if needed:
spring:
mvc:
static-path-pattern: /static/**Custom exception resolver:
@Component
public class ExceptionResolverConfig implements WebMvcConfigurer {
@Override
public void extendHandlerExceptionResolvers(List<HandlerExceptionResolver> resolvers) {
resolvers.remove(resolvers.size() - 1);
resolvers.add(new DefaultHandlerExceptionResolver() {
@Override
protected ModelAndView handleNoHandlerFoundException(NoHandlerFoundException ex,
HttpServletRequest request, HttpServletResponse response, Object handler) throws IOException {
ModelAndView mv = new ModelAndView(new View() {
@Override
public void render(Map<String, ?> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
response.getWriter().println(ex.getMessage());
}
});
return mv;
}
});
}
}Resulting unified JSON error response:
Other solutions exist; choose the one that fits your project requirements.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Spring Full-Stack Practical Cases
Full-stack Java development with Vue 2/3 front-end suite; hands-on examples and source code analysis for Spring, Spring Boot 2/3, and Spring Cloud.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
