SLF4J with Log4j Example

SLF4J binding with Log4j (slf4j-log4j)

Now we can experiment and swap different logger implementations, but your application code can remain the same. All we need is to add slf4j-log4j with another popular logger implementation, such as the Log4j.

package com.javavillage.slf4j;

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

public class SLF4JSample {

	private static Logger LOGGER = LoggerFactory.getLogger(SLF4JSample.class);
    public static void main(String[] args) {
        LOGGER.info("Hi, Welcome to SLF4J exmaple");
    }

}
for now I am adding below dependency for maven pom.xml
<dependency>
	<groupId>org.slf4j</groupId>
	<artifactId>slf4j-api</artifactId>
	<version>1.7.13</version>
</dependency>
<dependency>
	<groupId>org.slf4j</groupId>
	<artifactId>slf4j-log4j12</artifactId>
	<version>1.7.13</version>
</dependency>
log4j.properties
# Root logger option
log4j.rootLogger=INFO, file, stdout
	 
# Direct log messages to stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} [%t] %-5p:: %m%n

# Direct log messages to a log file
log4j.appender.file=org.apache.log4j.RollingFileAppender 
log4j.appender.file.File=F:\\App\\javavillage.log
log4j.appender.file.MaxFileSize=10000KB
log4j.appender.file.MaxBackupIndex=10
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} [%t] %-5p:: %m%n

project structure after maven build.

SLF4J with LOG4J workspace

Now you see logging output on STDOUT with INFO level..

2015-12-13 14:44:08 [main] INFO :: Hi, Welcome to SLF4J exmaple