Category: java
Logging in REST APIs
Published on 16 Jul 2026
Explanation
Logging is essential for monitoring REST APIs. It helps developers track incoming requests, outgoing responses, execution time, and errors. Spring Boot uses SLF4J with Logback as the default logging framework.
Code:
private static final Logger logger = LoggerFactory.getLogger(StudentController.class);
Explanation
Log incoming API requests inside controller methods. This helps identify which endpoint was called and with what parameters.
Code:
@GetMapping("/{id}")
public Student getStudent(@PathVariable Long id) {
logger.info("Fetching student with id: {}", id);
return service.getStudent(id);
}
Explanation
Log important business events such as successful database operations or API responses. Avoid logging sensitive information like passwords or tokens.
Code:
logger.info("Student created successfully with id {}", student.getId());
Explanation
Use a Spring HandlerInterceptor to log every request before it reaches the controller. This centralizes request logging across the application.
Code:
public class LoggingInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response,
Object handler) {
System.out.println(request.getMethod() + " " + request.getRequestURI());
return true;
}
}
Explanation
Use a Filter to log both request and response details, including execution time. This helps measure API performance.
Code:
@Component
public class LoggingFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response,
FilterChain filterChain) throws ServletException, IOException {
long start = System.currentTimeMillis();
filterChain.doFilter(request, response);
long end = System.currentTimeMillis();
System.out.println("Execution Time: " + (end - start) + " ms");
}
}