Using Log4j with Slf4j

Slf4J (Simple Logging Facade for Java) is a high level logging framework. It serves as an abstraction for various logging frameworks, allowing developers to switch to desired logging framework at deployment time. 


Log4j Configuration File

Shown below is the log4j configuration file to be used for our sample application. It is a regular log4j configuration file.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration>
    
    <appender name="console" class="org.apache.log4j.ConsoleAppender">
    	<param name="threshold" value="debug" />
        <layout class="org.apache.log4j.PatternLayout">
	    	<param name="conversionPattern" value="%m%n"/>
		</layout>
    </appender>
    
    <logger name="examples" additivity="false">
		<level value="debug"/>
    	<appender-ref ref="console"/>
    </logger>
    
    <root>
	<level value="debug" />
	<appender-ref ref="console"/>
    </root>
</log4j:configuration>

Dependency:

  • slf-api.jar
  • log4j.jar
  • slf4j-log4j.jar

Java Class

Below is our java class which is using slf4j to capture logging information. The slf4j logger is just an abstraction; log4j loggers are used behind the scene to capture the logging information.

package examples;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class TestLogging {
	
    public static Logger logger = LoggerFactory.getLogger(TestLogging.class);
	
    public static void main(String args[]){
		
	if(logger.isDebugEnabled()){
   	    logger.debug("This is a debug log message");
	}
    }
}
RELATED ARTICLES

Logging Different Priority Level Messages to Separate Files

Log4j can be configured to publish different priority level messages in separate files; developers can log error messages in a separate file thus reducing the effort of searching errors in large files

View Article

Introduction to Logging with Log4J

Log4j is an open-source logging framework that helps developers to capture logging statements in java applications. It is fully configurable and can be configured using external configuration files.

View Article

Integrating Log4J with Perf4J for Performance Logging

Perf4j is an open source logging framework used primarily for monitoring performance statistics in java applications. Log4j has the ability to integrate with perf4j to capture performance data.

View Article