Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lære Adding Logging to a Controller | Practical Logging in Spring Boot
Practice
Projects
Quizzes & Challenges
Quizzes
Challenges
/
Logging and Monitoring in Spring Applications

bookAdding Logging to a Controller

Adding logging to your Spring Boot controllers is essential for tracking user actions, diagnosing issues, and understanding application behavior. In this chapter, you will learn why controller-level logging matters, how to implement effective logging in your controllers, and best practices for capturing meaningful information without cluttering your logs. By the end, you will be able to add clear, actionable log statements to your controllers to support monitoring and troubleshooting in real-world applications.

Adding Logging to a Spring Boot Controller

Spring Boot makes it easy to add logging to any part of your application, including controllers. Logging in controllers helps you track requests, responses, and errors, making it easier to debug and maintain your application.

Why Log in Controllers?

  • Track incoming HTTP requests and outgoing responses;
  • Record important events, such as user actions or errors;
  • Help diagnose issues in production environments.

Setting Up Logging in a Controller

Use the built-in org.slf4j.Logger and org.slf4j.LoggerFactory classes for logging in Spring Boot. These are compatible with the default logging system and require no extra configuration.

Step 1: Import the Logger

Add the following imports at the top of your controller file:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

Step 2: Create a Logger Instance

Define a logger as a private static final field in your controller class:

private static final Logger logger = LoggerFactory.getLogger(YourController.class);

Replace YourController with the actual class name.

Step 3: Add Logging Statements

Use the logger to print messages at different levels, such as info, debug, or error:

@RestController
@RequestMapping("/api")
public class UserController {
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @GetMapping("/users/{id}")
    public ResponseEntity<User> getUser(@PathVariable Long id) {
        logger.info("Received request for user with id: {}", id);
        try {
            User user = userService.findById(id);
            logger.debug("User found: {}", user);
            return ResponseEntity.ok(user);
        } catch (UserNotFoundException e) {
            logger.error("User not found: {}", id);
            return ResponseEntity.notFound().build();
        }
    }
}

Key points from this example:

  • logger.info() records standard operations, such as receiving a request;
  • logger.debug() provides detailed information, useful for development and debugging;
  • logger.error() logs errors and exceptions, helping you track failures.

Practical Tips

  • Use placeholders ({}) in log messages to inject variable values;
  • Log at the appropriate level: use info for general events, debug for details, and error for failures;
  • Avoid logging sensitive information, such as passwords or personal data.

Adding logging to your controllers gives you clear visibility into how your application is being used and where problems may occur.

HelloController.java

HelloController.java

copy

Following these practices helps you keep logs clear, useful, and secure, making it easier to monitor and troubleshoot your Spring Boot application.

question mark

What is a recommended way to add logging to a Spring Boot controller?

Select the correct answer

Var alt klart?

Hvordan kan vi forbedre det?

Tak for dine kommentarer!

Sektion 2. Kapitel 1

Spørg AI

expand

Spørg AI

ChatGPT

Spørg om hvad som helst eller prøv et af de foreslåede spørgsmål for at starte vores chat

bookAdding Logging to a Controller

Stryg for at vise menuen

Adding logging to your Spring Boot controllers is essential for tracking user actions, diagnosing issues, and understanding application behavior. In this chapter, you will learn why controller-level logging matters, how to implement effective logging in your controllers, and best practices for capturing meaningful information without cluttering your logs. By the end, you will be able to add clear, actionable log statements to your controllers to support monitoring and troubleshooting in real-world applications.

Adding Logging to a Spring Boot Controller

Spring Boot makes it easy to add logging to any part of your application, including controllers. Logging in controllers helps you track requests, responses, and errors, making it easier to debug and maintain your application.

Why Log in Controllers?

  • Track incoming HTTP requests and outgoing responses;
  • Record important events, such as user actions or errors;
  • Help diagnose issues in production environments.

Setting Up Logging in a Controller

Use the built-in org.slf4j.Logger and org.slf4j.LoggerFactory classes for logging in Spring Boot. These are compatible with the default logging system and require no extra configuration.

Step 1: Import the Logger

Add the following imports at the top of your controller file:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

Step 2: Create a Logger Instance

Define a logger as a private static final field in your controller class:

private static final Logger logger = LoggerFactory.getLogger(YourController.class);

Replace YourController with the actual class name.

Step 3: Add Logging Statements

Use the logger to print messages at different levels, such as info, debug, or error:

@RestController
@RequestMapping("/api")
public class UserController {
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @GetMapping("/users/{id}")
    public ResponseEntity<User> getUser(@PathVariable Long id) {
        logger.info("Received request for user with id: {}", id);
        try {
            User user = userService.findById(id);
            logger.debug("User found: {}", user);
            return ResponseEntity.ok(user);
        } catch (UserNotFoundException e) {
            logger.error("User not found: {}", id);
            return ResponseEntity.notFound().build();
        }
    }
}

Key points from this example:

  • logger.info() records standard operations, such as receiving a request;
  • logger.debug() provides detailed information, useful for development and debugging;
  • logger.error() logs errors and exceptions, helping you track failures.

Practical Tips

  • Use placeholders ({}) in log messages to inject variable values;
  • Log at the appropriate level: use info for general events, debug for details, and error for failures;
  • Avoid logging sensitive information, such as passwords or personal data.

Adding logging to your controllers gives you clear visibility into how your application is being used and where problems may occur.

HelloController.java

HelloController.java

copy

Following these practices helps you keep logs clear, useful, and secure, making it easier to monitor and troubleshoot your Spring Boot application.

question mark

What is a recommended way to add logging to a Spring Boot controller?

Select the correct answer

Var alt klart?

Hvordan kan vi forbedre det?

Tak for dine kommentarer!

Sektion 2. Kapitel 1
some-alt