In this post I am going to share how to use Simple Logging Facade for Java (SLF4J) for logging in Spring Boot projects. It is very easy to use if you are using Lombok library in your project.
First let us understand what is SLF4J.
The Simple Logging Facade for Java (SLF4J) serves as a simple facade or abstraction for various logging frameworks (e.g.
http://www.slf4j.org/java.util.logging
,logback
,log4j
) allowing the end-user to plug in the desired logging framework at deployment time
Now, let us look into how we can use it.
If you have experience in using Lombok library, you will know how easy it is to use it and how manageable your code becomes.
‘It’ automatically plugs into your editor and build tools, spicing up your java. Never write another getter or equals method again, with one annotation your class has a fully-featured builder, Automate your logging variables, and much more.
https://projectlombok.org/
@Slf4j
Use the annotation @Slf4J
as shown below.
@Slf4j
public class LogExample {
// Your code goes here
}
When you use the annotation @Slf4J
, this is what it does for you. It generates:
public class LogExample {
private static final org.slf4j.Logger log = org.slf4j.LoggerFactory.getLogger(LogExample.class);
// Your code goes here
}
You need not have to instantiate LoggerFactory
on your own. You can directly use the log object directly as shown below.
public class LogExample {
// Your code goes here
try{
log.info("Log some information.");
}
catch(Exception e){
// do something when exception is thrown
}
}