Monday, July 22, 2013

Using Logback with Spring

The mandatory logging dependency in Spring is the Jakarta Commons Logging API (JCL). The nice thing about commons-logging is that you don't need anything else to make your application work. It has a runtime discovery algorithm that looks for other logging frameworks in well known places on the classpath and uses one that it thinks is appropriate (or you can tell it which one if you need to). If nothing else is available you get pretty nice looking logs just from the JDK (java.util.logging or JUL for short).

Unfortunately, the runtime discovery algorithm in commons-logging, while convenient for the end-user, is problematic. Switching off commons-logging is easy: just make sure it isn't on the classpath at runtime.
<dependencies> 
  <dependency> 
    <groupId>org.springframework</groupId> 
    <artifactId>spring-context</artifactId> 
    <version>${spring.version}</version> 
    <exclusions> 
      <exclusion> 
        <groupId>commons-logging</groupId> 
        <artifactId>commons-logging</artifactId> 
      </exclusion> 
    </exclusions> 
  </dependency> 
</dependencies> 
Now this application is probably broken because there is no implementation of the JCL API on the classpath, so to fix it a new one has to be provided.Logback is very powerfull logging framework and is intended as a successor to the popular log4j project. Logback implements SLF4J api so we need slf4j-jcl brindge on classpath.
Final dependencies are:
<dependencies> 
  <dependency> 
    <groupId>org.springframework</groupId> 
    <artifactId>spring-context</artifactId> 
    <version>${spring.version}</version> 
    <exclusions> 
      <exclusion> 
        <groupId>commons-logging</groupId> 
        <artifactId>commons-logging</artifactId> 
      </exclusion> 
    </exclusions> 
  </dependency> 
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>jcl-over-slf4j</artifactId>
    <version>${jcl.over.slf4j.version}</version>  
  </dependency>
<dependency>
    <groupId>ch.qos.logback</groupId>
    <artifactId>logback-classic</artifactId>
    <version>${logback.version}</version>
  </dependency>
</dependencies> 

No comments:

Post a Comment