Logging With SLF4J
Learn how to use the Simple Logging Facade for Java (SLF4J) in your applications.
The Simple Logging Facade for Java (SLF4J) serves as a simple facade or abstraction for various logging frameworks. It allows you to code while depending on just one dependency, namely "slf4j-api.jar", and to plug in the desired logging framework at runtime. It is very simple to use slf4 logging in your application. You just need to create a slf4j logger and invoke its methods.
Following is a sample code,
package com.test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class Main {
private static final Logger logger = LoggerFactory.getLogger(Main.class);
public static void main(String[] args) {
logger.info("Testing 123");
}
}
You have to add the following dependency in your pom.xml file
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.13</version>
</dependency>
This is the bare minimum configuration you need to enable sl4fj logging. But if you run this code. you will get a warning similar to the below.
SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder".
SLF4J: Defaulting to no-operation (NOP) logger implementation
SLF4J: See http://www.slf4j.org/codes.html#StaticLoggerBinder for further details.
This is because, it can't find a binding in the class path, by default, if it can't find a binding in the class path, it will bind to no-op logger implementation.
Using java.util.logging
If you want to use the binding for java.util.logging in your code, you only need to add the following dependency in to your pom.file.
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-jdk14</artifactId>
<version>1.7.13</version>
</dependency>
This will output the following,
INFO: Testing 123
Using Log4j
If you want to use the binding for log4j version 1.2 in your code, you only need to add the following dependency in to your pom.file.
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.13</version>
</dependency>
Log4j needs an appender to log. Hence, you have to specify the log4j properties.
Create the file "log4j.properties", in resource directory of your project and add the following into it.
# Set root logger level to DEBUG and its only appender to A1.
log4j.rootLogger=DEBUG, A1
# A1 is set to be a ConsoleAppender.
log4j.appender.A1=org.apache.log4j.ConsoleAppender
# A1 uses PatternLayout.
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n
This will output the following,
0 [main] INFO com.test.Main - Testing 123
[1] http://www.slf4j.org/
[2] http://logging.apache.org/log4j/1.2/index.html
Opinions expressed by DZone contributors are their own.