Java: Config slf4j and log4j in Maven Project

Categories: Java November 10th, 2014 23:29

1. Config Maven dependences


    <dependency>         <groupId>org.slf4j</groupId>         <artifactId>slf4j-api</artifactId>         <version>1.7.7</version>     </dependency>
      <dependency>        <groupId>org.slf4j</groupId>        <artifactId>slf4j-log4j12</artifactId>
       <version>1.7.7</version>
    </dependency>

2. Setup log4j configuration

src/main/resources/log4j.xml (log4j.properties):

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
   <appender name="console" class="org.apache.log4j.ConsoleAppender">
     <param name="Target" value="System.out"/>
     <layout class="org.apache.log4j.PatternLayout">
       <param name="ConversionPattern" value="%d %-5p %c{1} - %m%n"/>
     </layout>
   </appender>

  <root>
     <priority value ="debug" />
     <appender-ref ref="console" />
   </root>
</log4j:configuration>

or log4j.properties

log4j.rootLogger=DEBUG, STDOUT
log4j.logger.deng=INFO
log4j.appender.STDOUT=org.apache.log4j.ConsoleAppender
log4j.appender.STDOUT.layout=org.apache.log4j.PatternLayout
log4j.appender.STDOUT.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n

3. Initialize Logger and use it

package com.liguoliang.log;

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

public class LogTest {

	static Logger LOGGER = LoggerFactory.getLogger(LogTest.class);
	
	public static void main(String[] args) {
		LOGGER.info("slf4j test info");
	}
}

output:

2014-11-10 23:07:39,624 INFO  LogTest - slf4j test info

<->



// Proudly powered by Apache, PHP, MySQL, WordPress, Bootstrap, etc,.