Hackforge Academy

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");
    }
}

πŸš€ Learn Spring Boot with real-world projects

πŸ’‘ Build REST APIs step by step

🧠 Improve backend development skills

🎯 Get career-ready practical training

Join Our Free WhatsApp Community

Direct access to niche-specific mentors and peers on WhatsApp.

🐍

Python Community

Discuss Django, FastAPI, AI integration, and automation scripts with 15k+ developers.

Join Python Community
βš›οΈ

React Community

Master Next.js, Framer Motion, and State Management. Share your latest UI components.

Join React Community
β˜•

Java Community

Deep dives into Spring Boot, Microservices architecture, and high-performance backend ops.

Join Java Community