Home » Spring boot slf4j annotation

Spring boot slf4j annotation

  • by
Spring boot slf4j annotation

1. Overview

In this article, we will learn the purpose of Spring boot slf4j annotation. Project Lombok is an annotation library that aims to reduce the boilerplate code by replacing them with a simple set of annotations.

2. Spring slf4j annotation

The @slf4j annotation causes Lombok to generate a logger field. This annotation does not work in Kotlin class files. The slf4j annotation applies to Java but does not work with Kotlin class files.

To use this annotation, Lombok dependency must be in the classpath.

<dependency>
	<groupId>org.projectlombok</groupId>
	<artifactId>lombok</artifactId>
	<optional>true</optional>
</dependency>

2.1. Logger field without @ slf4j annotation

Usually, we create a logger by using the LoggerFactory class for displaying the log statements.

For example, the following controller class has a private field logger which is used in the class for logging.

@RestController
public class EmployeeController {
    private Logger log = LoggerFactory.getLogger(EmployeeController.class.getName());
    @GetMapping("/name")
    public String getName() {
        log.info("Get name handler method called");
        return "Employee";
    }
}

2.2. Use @ slf4j annotation in Spring boot

You can omit writing the logger field and initialization by using the @Slf4j annotation.

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
public class EmployeeController {
    @GetMapping("/name")
    public String getName() {
        log.info("Get name handler method called");
        return "Employee";
    }
}

3. Conclusion

To sum up, we have learned the @Slf4j Lombok annotation in a Java application. You can refer to our GitHub repository for code samples.

Leave a Reply

Your email address will not be published. Required fields are marked *