项目说明

Commons Logging

The Apache Commons Logging (JCL) provides a Log interface that is intended to be both light-weight and an independent abstraction of other logging toolkits. It provides the middleware/tooling developer with a simple logging abstraction, that allows the user (application developer) to plug in a specific logging implementation.

SLF4J

The Simple Logging Facade for Java (SLF4J) serves as a simple facade or abstraction for various logging frameworks (e.g. java.util.logging, logback, log4j) allowing the end user to plug in the desired logging framework at deployment time.

结论

通过以上说明可以看出他们两个的目的都是一样的,那就是提供统一的日志API供程序调用,而不用关注底层具体使用的是哪个Log Provider。这样就可以随你喜欢,用Log4j或是Logback。

API说明

Commons Logging Api

1
2
Log log = LogFactory.getLog();
log.debug("log");

SLF4J Api

1
2
Logger logger = LoggerFactory.getLogger();
logger.debug("log");

添加具体的Log实现库

在具体使用时,还需将Log Provider加入到Classpath里,比如Log4j,Logback。

怎么知道调用哪个实现库的呢

来看看Commons Logging的源代码,来了解一下是怎么知道究竟调用哪一个Log Provider的。

1
2
3
4
5
6
7
8
9
10
11
12
//代码在org.apache.commons.logging.impl.LogFactoryImpl.java文件
private static final String LOGGING_IMPL_LOG4J_LOGGER = "org.apache.commons.logging.impl.Log4JLogger";
private static final String[] classesToDiscover = {
LOGGING_IMPL_LOG4J_LOGGER,
"org.apache.commons.logging.impl.Jdk14Logger",
"org.apache.commons.logging.impl.Jdk13LumberjackLogger",
"org.apache.commons.logging.impl.SimpleLog"
};
for(int i=0; i<classesToDiscover.length && result == null; ++i) {
result = createLogFromClass(classesToDiscover[i], logCategory, true);
}
c = Class.forName(logAdapterClassName, true, currentCL);

可以看出,Commons Logging会在程序启动后进行试加载,一旦有某个Log Provider在Classpath下,就会加载成功。