Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
Lernen Adding Logging to a Controller | Practical Logging in Spring Boot
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

War alles klar?

Wie können wir es verbessern?

Danke für Ihr Feedback!

Abschnitt 2. Kapitel 1

Fragen Sie AI

expand

Fragen Sie AI

ChatGPT

Fragen Sie alles oder probieren Sie eine der vorgeschlagenen Fragen, um unser Gespräch zu beginnen

Suggested prompts:

Can you show more examples of logging in different controller methods?

What are some common mistakes to avoid when logging in controllers?

How can I configure log levels for my Spring Boot application?

bookAdding Logging to a Controller

Swipe um das Menü anzuzeigen

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

War alles klar?

Wie können wir es verbessern?

Danke für Ihr Feedback!

Abschnitt 2. Kapitel 1
some-alt