Spring Boot Logging Essentials: Getting Started with @Slf4j

Anil R
2 min readDec 6, 2024

--

@Slf4j is a Lombok annotation that simplifies logging in Java applications. It provides a Logger instance named log that can be used directly in your class, reducing boilerplate code for initializing loggers.

Usage of @Slf4j

  1. Automatically creates a logger instance named log for the class.
  2. Integrates with SLF4J (Simple Logging Facade for Java), enabling flexible logging configurations with implementations like Logback, Log4j, or java.util.logging.
  3. Eliminates manual declaration of logger objects.

Basic Usage

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

@Slf4j
@Component
public class ProcessService {

public void process() {
log.info("started");
try {
int result = 200 / 2;
log.debug("result: {}", result);
} catch (Exception e) {
log.error("Error occurred: {}", e.getMessage(), e);
}
log.info("completed");
}
}

Parameterized Logging

log.info("User {} logged in at {}", id, time);

Custom Logging Levels

log.trace("This is a TRACE message");
log.debug("This is a DEBUG message");
log.info("This is an INFO message");
log.warn("This is a WARN message");
log.error("This is an ERROR message");

Best Practices for Using @Slf4j

Use Appropriate Log Levels:

  • TRACE: For very detailed diagnostic information.
  • DEBUG: For debugging purposes.
  • INFO: For general operational messages.
  • WARN: For potentially harmful situations.
  • ERROR: For errors and exceptions.

Avoid Logging Sensitive Information:

  • Ensure personally identifiable information (PII) or sensitive data like passwords are not logged.

Use Parameterized Messages:

  • Always use {} placeholders to avoid unnecessary computation when the log level is disabled.

Avoid Excessive Logging:

  • Overuse of DEBUG or INFO in performance-critical sections can lead to performance bottlenecks.

Configure Logging Properly:

  • Use a proper logging configuration file (e.g., logback.xml or application.properties) to manage log levels and formats.

Test Log Output:

  • Ensure logs appear correctly in your preferred format and destinations (console, file, etc.).

Avoid Static Logging in Libraries:

  • If creating reusable libraries, avoid static loggers and let the client application configure logging.

Advantages of Using @Slf4j

  • Reduces boilerplate code for initializing loggers.
  • Provides consistent logger naming (log) across the application.
  • Compatible with all SLF4J-compliant logging frameworks.
  • Simplifies integration with Spring Boot, where SLF4J is the default logging API.

--

--

Anil R
Anil R

Written by Anil R

Full Stack Developer with 15 years experience.

No responses yet