Using @Slf4j annotation for logging

Introduction

In this tutorial, we will provide a short example of using the SLF4J logging library with the annotations provided by Project Lombok.

What do we create?

SLF4J, which stands for Simple Logging Facade for Java is a library that provides a simple and flexible abstraction for logging in applications. Instead of being a logging framework itself, SLF4J is a facade or a bridge that allows you to plug in the logging framework of your choice (e.g. Log4j) at deployment time without changing the application code.

Project Lombok is a popular Java library designed to reduce boilerplate code in our applications. It achieves this by generating repetitive and commonly-used methods at compile time using annotations. This means you can write less code while keeping your classes clean and readable.

In this tutorial we will build a simple project example that demonstrates how to use both libraries. We will see that a lot of boilerplate code is reduced and we can have classes that are cleaner and more readable.

How do we create it?

We can start by creating a new Gradle Project. In the build.gradle file, we need to add the following dependencies: Project Lombok dependency, SLF4J, Log4j and the binding between SLF4J and Log4J. The ‘application’ plugin is used to simplify the execution of our application. The project will run with a “gradle run” command typed in the command line or through the user interface of your own IDE.

				
					plugins {
    id 'java'
    id 'application'
}

group 'org.explainjava'
version '1.0'

repositories {
    mavenCentral()
}

application {
    mainClassName = "org.explainjava.Main"
}

dependencies {
    // Lombok project
    compileOnly 'org.projectlombok:lombok:1.18.36'
    annotationProcessor 'org.projectlombok:lombok:1.18.28'

    // SLF4J API
    implementation 'org.slf4j:slf4j-api:2.0.9'

    // Log4j binding for SLF4J
    runtimeOnly 'org.slf4j:slf4j-log4j12:2.0.9'

    // Log4j core library
    runtimeOnly 'log4j:log4j:1.2.17'

}
				
			

The next step is to create a log4j.properties configuration file in our project’s src/main/resources directory.

				
					# Root logger configuration
log4j.rootLogger=INFO, console, file

# Console appender
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.console.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

# File appender
log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file.file=application.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
				
			

Now, we can test the log in the Main class of our application:.

				
					@Slf4j
public class Main {

    public static void main(String[] args) {
        log.info("Application is starting...");

        try {
            log.debug("Attempting risky operation...");
            int result = 10 / 0; // This will throw an exception
        } catch (Exception e) {
            log.error("An exception occurred: {}", e.getMessage(), e);
        }

        log.info("Application is shutting down.");
    }
}
				
			

We can see that we don’t have to manually declare a logger. We only need to add a simple @Slf4j annotation and Project Lombok will declare it for us. This significantly reduces the boilerplate code which is required to declare the log. 

If we will run the application using “gradle run” command, the output will be:

				
					2024-11-29 16:35:20 INFO  Main:11 - Application is starting...
2024-11-29 16:35:20 ERROR Main:17 - An exception occurred: / by zero
java.lang.ArithmeticException: / by zero
	at org.explainjava.Main.main(Main.java:15)
2024-11-29 16:35:20 INFO  Main:20 - Application is shutting down.
				
			

Conclusion

In this tutorial we had a step by step example of configuring SLF4J and Lombok Project libraries to improve the logging method of an application.