【Java.ThirdParty】日志——Slf4j的几种应用模式




基本使用规则

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>


工程中引入了3个新的jar包:




同样对于Log4j,需要相应的配置文件log4j.xml或log4j.properties。



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值