commons-logging vs log4j

今天使用日志记录的时候突然发现,系统中有2套获取日志记录对象的方法,

1
2
3
4
5
// using org.apache.commons.logging
Log logger = LogFactory.getLog(XXX.class);

// using org.apache.log4j
Logger logger = Logger.getLogger(XXX.class);

这2者间有什么区别呢?

叫人疑惑,上网搜了下,找到了 commons-logging (org.apache.commons.logging) 的说明文档

The Logging Component

When writing a library it is very useful to log information. However there are many logging implementations out there, and a library cannot impose the use of a particular one on the overall application that the library is a part of.

The Logging package is an ultra-thin bridge between different logging implementations. A library that uses the commons-logging API can be used with any logging implementation at runtime. Commons-logging comes with support for a number of popular logging implementations, and writing adapters for others is a reasonably simple task.

Applications (rather than libraries) may also choose to use commons-logging. While logging-implementation independence is not as important for applications as it is for libraries, using commons-logging does allow the application to change to a different logging implementation without recompiling code.

Note that commons-logging does not attempt to initialise or terminate the underlying logging implementation that is used at runtime; that is the responsibility of the application. However many popular logging implementations do automatically initialise themselves; in this case an application may be able to avoid containing any code that is specific to the logging implementation used.

简单的说,commons-logging是一个桥接器,可以在运行时自动加载具体的log实现框架,实现应用程序对具体log实现框架的依赖。这样的好处是,更换log实现框架不需要重新编译你的程序。

So,

1
Log logger = LogFactory.getLog(XXX.class);

is better than

1
Logger logger = Logger.getLogger(XXX.class);

(旧文迁移)