基本使用规则
Embedded components such as libraries or frameworks should not declare a dependency on any SLF4J binding but only depend on slf4j-api.
(程序代码中不要引用具体的log实现如log4j等,只能引入slf4j-api中的接口;)
典型使用模式
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class HelloWorld {
public static void main(String[] args) {
Logger logger = LoggerFactory.getLogger(HelloWorld.class);
logger.info("Hello World");
}
}
Slf4j如何定位具体使用哪个Log Binding
使用slf4j的LoggerFactory获得Logger对象是,有如下的调用栈:
主要的绑定发生在函数bind()中,
// the next line does the binding
StaticLoggerBinder.getSingleton();
StaticLoggerBinder并不存在于slf4j-api-x.x.x.jar中;查看与日志系统对应的adaption jar包,如slf4j-log4j12-x.x.x.jar,就会发现,相应的jar包中都有一个org.slf4j.impl。StaticLoggerBinder的实现。
在函数getILoggerFactory()中,返回的实际上是对应adaption jar包中的LoggerFactory实现:
StaticLoggerBinder.getSingleton().getLoggerFactory();
如上实现了所谓的静态绑定,达到只要选取不同jar包就能简单灵活配置的目的。
Slf4j + Log4j
如果希望底层日志框架使用log4j,只需要在pom.xml中声明“org.slf4j:slf4j-log4j12”作为一个dependency。这个声明除了会引入slf4j-log4j12-x.x.x.jar之外,还会引入slf4j-api-x.x.x.jar和log4j-1.2.x.jar。(可以显式声明slf4j-api和log4j的dependency。)
<!-- SLF4J + LOG4J -->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.7</version>
</dependency>
同样对于Log4j,需要相应的配置文件log4j.xml或log4j.properties。