Slf4j
A library which provide a central interface for facade to use between different logging libraries.
See Slf4j vs JUL vs Logback vs Log4j
Example
Logging with JUL
package dev.auspham.logging;
import java.util.logging.Level;
import java.util.logging.Logger;
public class Application {
private static final Logger logger = Logger.getLogger(Application.class.getName());
public static void main(String[] args) {
logger.log(Level.INFO, "hello world");
}
}
Logging with Slf4j
Install:
implementation('org.slf4j:slf4j-api:2.0.10')
[!note]
When using without SpringBoot, we have to specify the version of the library.
We can then change the syntax to this:
package dev.auspham.logging;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Application {
public static final Logger logger = LoggerFactory.getLogger(Application.class);
public static void main(String[] args) {
logger.info("Hello world");
}
}
Doing this right now when running it would not work because there is no provider provided:
BUILD SUCCESSFUL in 160ms
2 actionable tasks: 2 executed
SLF4J(W): No SLF4J providers were found.
SLF4J(W): Defaulting to no-operation (NOP) logger implementation
SLF4J(W): See https://www.slf4j.org/codes.html#noProviders for further details.
To do this, we need to install the relevant package that we have, in our case is
implementation('org.slf4j:slf4j-jdk14:2.0.10')
for JUL. As a result, it will print out Hello World
Using with Spring
Note, in SpringBoot, by default it's using LogBack, therefore, we can just use Slf4j and it will just work out of the box and integrate with LogBack as the provider.
@Component
public class MyComponent {
private static final Logger logger = LoggerFactory.getLogger(MyComponent.class);
public MyComponent() {
logger.info(logger.getClass().getName());
logger.info("My component is created");
}
}
2024-03-11T12:39:39.315+11:00 INFO 165647 --- [ restartedMain] dev.auspham.model.MyComponent : ch.qos.logback.classic.Logger
2024-03-11T12:39:39.315+11:00 INFO 165647 --- [ restartedMain] dev.auspham.model.MyComponent : My component is created
The @Slf4j
The @Slf4j
tag is in project Lombok which automatically generate the static final Logger logger
for us. To use it, we can do the following:
So instead of the above, we can just do:
plugins {
...
id 'io.freefair.lombok' version '8.6'
}
package dev.auspham.logging;
import lombok.extern.slf4j.Slf4j;
@Slf4j
public class Application {
public static void main(String[] args) {
log.info("Hello world");
}
}