As you already know, Spring framework uses Commons Logging (JCL, the J stands for Jakarta, the former house for Apache Java solutions) as the framework for logging, mainly for historical reasons and backward compatibility.
But it’s possible to use another framework easily thanks to the existing binding process for most of the popular frameworks.
Log4J
If you want to use the classic and popular framework it’s very easy, since Log4J can be used directly with JCL (I’d rather commons-logging, BTW)
Just add the dependency, no need of excluding anything from Spring. For instance, in a maven project:
1 2 3 4 5 6 7 8 9 10 11 |
<dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.0.6.RELEASE</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> |
Don’t forget to put a configuration file ( log4j.properties or log4j.xml) in the root of the classpath.
SLF4J with Logback
These two frameworks have became my favourite ones for Java logging.
However, in order to use them, you have to make a little bit more changes.
- Exclude CL from Spring
- Bridging legacy logging APIs, that is, redirect log4j and java.util.logging calls to SLF4J.
- Include the SLF4J API dependency
- Include the Logback dependency
Since Logback implements SLF4J natively, there is no need of further binding.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 |
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.0.6.RELEASE</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>1.7.7</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>log4j-over-slf4j</artifactId> <version>1.7.7</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.7</version> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.1.2</version> </dependency> |
Finally, you can configure logback with a logback.groovy in the classpath, a logback-test.xml in the classpath, a logback.xml in the classpath or using the BasicConfigurator.
Spring provides instructions to use SLF4J with Log4J and there is a great explanation for the bindings at SLF4J logging with Log4J and JCL