Pages

Monday, April 28, 2014

Configuring SLF4J with Log4J2 using Maven

In our current project we had to decide for a logging framework. As it apears to be a common standard to use the Simple Logging Facade for Java (SLF4J) on caller side, there were various options on the logging framework itself. In the end we decided to use Log4J 2 as logging framework, mainly for reasons of better performance in comparison to other frameworks (see The Logging Olympics).
The setup of this combination is fairly ease, and there are good examples how to add a SLF4J binding to your Maven project as in this good blog article. But as Log4J is rather new and no final release has been announced yet (current is release candidate 1), it's hard to find a definitive configuration example, so I decided to put down ours.

<properties>
  <slf4j.version>1.7.6</slf4j.version>
  <!-- current log4j 2 release -->
  <log4j.version>2.0-rc1</log4j.version> 
</properties>
...
<dependencies>
  <dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>${slf4j.version}</version>
  </dependency>
  <!-- Binding for Log4J -->
  <dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-slf4j-impl</artifactId>
    <version>${log4j.version}</version>
  </dependency>
  <!-- Log4j API and Core implementation required for binding -->
  <dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-api</artifactId>
    <version>${log4j.version}</version>
  </dependency>
  <dependency>
    <groupId>org.apache.logging.log4j</groupId>
    <artifactId>log4j-core</artifactId>
    <version>${log4j.version}</version>
  </dependency>
</dependencies> 

And a basic log4j configuration (located at your src/main/resources path) could look like this
<?xml version="1.0" encoding="UTF-8"?>
<configuration status="OFF">
 <appenders>
  <Console name="Console" target="SYSTEM_OUT">
   <PatternLayout pattern="%d{HH:mm:ss} [%t] %-5level %logger{36} - %msg%n" />
  </Console>
 </appenders>
 <Loggers>
  <Logger name="yourLogger" level="debug" additivity="false">
   <AppenderRef ref="Console" />
  </Logger>
  <Root level="error">
   <AppenderRef ref="Console" />
  </Root>
 </Loggers>
</configuration>

No comments: