Friday, September 27, 2013

log4j 2.0 configuration with Spring


Log4j 2.x has several improvements over Log4j 1.x to catch up with other log frameworks like slf4j, logback.

Spring reference documentation has details on how to configure logging including details on configuration for log4j.  Though the reference documentation mentions that the only logging dependency is JCL, there are few spring projects that use slf4j (for e.g., spring-data-* projects). And also many popular frameworks use slf4j.  Hence it is most likely that slf4j is used in any application directly or indirectly.

As per the spring reference documentation, to configure log4j with spring and slf4j, we need  four jars included as maven dependency viz., jcl-over-slf4j, slf4j-api, slf4j-log4j12, log4j.  The maven dependencies are specified as below.
 <dependency>  
      <groupId>org.slf4j</groupId>  
      <artifactId>jcl-over-slf4j</artifactId>  
      <version>${slf4j.version}</version>  
      <scope>runtime</scope>  
     </dependency>  
     <dependency>  
      <groupId>org.slf4j</groupId>  
      <artifactId>slf4j-api</artifactId>  
      <version>${slf4j.version}</version>  
      <scope>runtime</scope>  
     </dependency>  
     <dependency>  
      <groupId>org.slf4j</groupId>  
      <artifactId>slf4j-log4j12</artifactId>  
      <version>${slf4j.version}</version>  
      <scope>runtime</scope>  
     </dependency>  
     <dependency>  
      <groupId>log4j</groupId>  
      <artifactId>log4j</artifactId>  
      <version>1.2.14</version>  
      <scope>runtime</scope>  
     </dependency>  


However, log4j 2.x has an adapter for slf4j.  To achieve the same, log4j 2.x require to configure 3 jars as maven dependency.   The required jars are jcl-over-slf4j, log4j-slf4j-impl, log4j-core. The maven dependencies are as specified below.
                <dependency>  
                     <groupId>org.slf4j</groupId>  
                     <artifactId>jcl-over-slf4j</artifactId>  
                     <version>${slf4j.version}</version>  
                     <scope>runtime</scope>  
                </dependency>  
                <dependency>  
                     <groupId>org.apache.logging.log4j</groupId>  
                     <artifactId>log4j-slf4j-impl</artifactId>  
                     <version>${log4j.version}</version>  
                </dependency>  
                <dependency>  
                     <groupId>org.apache.logging.log4j</groupId>  
                     <artifactId>log4j-core</artifactId>  
                     <version>${log4j.version}</version>  
                </dependency>