slf4j 简介

看spring samples(https://src.springframework.org/svn/spring-samples/)的时候,发现pom.xml中引用到self4j,用以替换commons logging,之前看到hibernate也有用到slf4j,于是决定了解一下这个组件。

http://www.slf4j.org/

Simple Logging Facade for Java (SLF4J)

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

与commons logging类似,self4j只定义一套日志接口标准,与具体的实现分离,可以使用不同的实现如:log4j,java.util.logging,logback...

甚至self4j可以再绑定到commons logging接口,把日志任务交给commons logging及其实现。

self4j与common logging最大区别在于:self4j使用编绎时绑定,而commons logging使用类加载的方式,大多情况下,self4j效率会较高一些。

从使用者的语法上看:

以前commons logging的用法是:

if(logger.isDebugEnabled()){
  logger
.debug("Entry number: "+ i +" is "+String.valueOf(entry[i]));
}

而sel4j的写法是:

logger.debug("The new entry is {}. It replaces {}.", entry, oldEntry);

这种 形式,无需要检查logger enable,可变参数自动填充,类似于c#的作法。

据说 commons logging的开发已经不活跃了。

logback VS log4j

logback 与 log4j都是日志的一个具体实现,而且出自同一作者。据说前者效率高很多倍,logback是后来居上。

logback是 slf4j api的本地实现,应该与slf4j api融合得更好,用官网的话是:“logback-classic speaks SLF4J natively” 。

Reasons to prefer logback over log4j 

http://logback.qos.ch/reasonsToSwitch.html

 

Logback's architecture

http://logback.qos.ch/manual/architecture.html

Logback's basic architecture is sufficiently generic so as to apply under different circumstances. At the present time, logback is divided into three modules, logback-core, logback-classic and logback-access.

The core module lays the groundwork for the other two modules.

The classic module extends core. The classic module corresponds to a significantly improved version of log4j. Logback-classic natively implements the SLF4J API so that you can readily switch back and forth between logback and other logging systems such as log4j or java.util.logging (JUL) introduced in JDK 1.4.

The third module called access integrates with Servlet containers to provide HTTP-access log functionality. A separate document covers access module documentation.

In the remainder of this document, we will write "logback" to refer to the logback-classic module.

 

如果项目已经使用log4j,而想尝试换使用sel4j,可以使用一个工具:

SLF4J Migrator

http://www.slf4j.org/migrator.html

 

最后引用一个图,出自官网User Manual,很直观:
click to enlarge

 

posted @ 2013-01-24 10:21  庚武  Views(727)  Comments(0Edit  收藏  举报