浅谈Java日志框架slf4j作用及其实现原理

2025-05-29 0 66

slf4j是一个日志框架抽象层,底下绑定具体的日志框架,比如说log4j,logback,java logging api等。slf4j也有自身的默认实现,但是我们还是主要以日志框架抽象层的身份使用slf4j

要使用slf4j,得包含对"org.slf4j:slf4j-api"的依赖。

简单回顾门面模式

slf4j是门面模式的典型应用,因此在讲slf4j前,我们先简单回顾一下门面模式,

门面模式,其核心为外部与一个子系统的通信必须通过一个统一的外观对象进行,使得子系统更易于使用。用一张图来表示门面模式的结构为:

浅谈Java日志框架slf4j作用及其实现原理

门面模式的核心为facade即门面对象,门面对象核心为几个点:

  1. 知道所有子角色的功能和责任
  2. 将客户端发来的请求委派到子系统中,没有实际业务逻辑
  3. 不参与子系统内业务逻辑的实现

大致上来看,对门面模式的回顾到这里就可以了,开始接下来对slf4j的学习。

我们为什么要使用slf4j

我们为什么要使用slf4j,举个例子:

我们自己的系统中使用了logback这个日志系统

我们的系统使用了a.jar,a.jar中使用的日志系统为log4j

我们的系统又使用了b.jar,b.jar中使用的日志系统为slf4j-simple

这样,我们的系统就不得不同时支持并维护logback、log4j、slf4j-simple三种日志框架,非常不便。

解决这个问题的方式就是引入一个适配层,由适配层决定使用哪一种日志系统,而调用端只需要做的事情就是打印日志而不需要关心如何打印日志,slf4j或者commons-logging就是这种适配层,slf4j是本文研究的对象。

从上面的描述,我们必须清楚地知道一点:slf4j只是一个日志标准,并不是日志系统的具体实现。理解这句话非常重要,slf4j只提做两件事情:

  1. 提供日志接口
  2. 提供获取具体日志对象的方法

slf4j-simple、logback都是slf4j的具体实现,log4j并不直接实现slf4j,但是有专门的一层桥接slf4j-log4j12来实现slf4j

为了更理解slf4j,我们先看例子,再读源码,相信读者朋友会对slf4j有更深刻的认识。

slf4j应用举例

上面讲了,slf4j的直接/间接实现有slf4j-simple、logback、slf4j-log4j12,我们先定义一个pom.xml,引入相关jar包:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51
<!-- 原文:五月的仓颉http://www.cnblogs.com/xrq730/p/8619156.html -->

<project xmlns="http://maven.apache.org/pom/4.0.0" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance"

xsi:schemalocation="http://maven.apache.org/pom/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">

<modelversion>4.0.0</modelversion>

<groupid>org.xrq.log</groupid>

<artifactid>log-test</artifactid>

<version>1.0.0</version>

<packaging>jar</packaging>

<name>log-test</name>

<url>http://maven.apache.org</url>

<properties>

<project.build.sourceencoding>utf-8</project.build.sourceencoding>

</properties>

<dependencies>

<dependency>

<groupid>junit</groupid>

<artifactid>junit</artifactid>

<version>4.11</version>

<scope>test</scope>

</dependency>

<dependency>

<groupid>org.slf4j</groupid>

<artifactid>slf4j-api</artifactid>

<version>1.7.25</version>

</dependency>

<dependency>

<groupid>ch.qos.logback</groupid>

<artifactid>logback-classic</artifactid>

<version>1.2.3</version>

</dependency>

<dependency>

<groupid>org.slf4j</groupid>

<artifactid>slf4j-simple</artifactid>

<version>1.7.25</version>

</dependency>

<dependency>

<groupid>log4j</groupid>

<artifactid>log4j</artifactid>

<version>1.2.17</version>

</dependency>

<dependency>

<groupid>org.slf4j</groupid>

<artifactid>slf4j-log4j12</artifactid>

<version>1.7.21</version>

</dependency>

</dependencies>

</project>

写一段简单的java代码:

?

1

2

3

4

5
@test

public void testslf4j() {

logger logger = loggerfactory.getlogger(object.class);

logger.error("123");

}

接着我们首先把上面pom.xml的第30行~第49行注释掉,即不引入任何slf4j的实现类,运行test方法,我们看一下控制台的输出为:

浅谈Java日志框架slf4j作用及其实现原理

看到没有任何日志的输出,这验证了我们的观点:slf4j不提供日志的具体实现,只有slf4j是无法打印日志的。

接着打开logback-classic的注释,运行test方法,我们看一下控制台的输出为:

浅谈Java日志框架slf4j作用及其实现原理

看到我们只要引入了一个slf4j的具体实现类,即可使用该日志框架输出日志。

最后做一个测验,我们把所有日志打开,引入logback-classic、slf4j-simple、log4j,运行test方法,控制台输出为:

浅谈Java日志框架slf4j作用及其实现原理

和上面的差别是,可以输出日志,但是会输出一些告警日志,提示我们同时引入了多个slf4j的实现,然后选择其中的一个作为我们使用的日志系统。

从例子我们可以得出一个重要的结论,即slf4j的作用:只要所有代码都使用门面对象slf4j,我们就不需要关心其具体实现,最终所有地方使用一种具体实现即可,更换、维护都非常方便。

slf4j实现原理

上面看了slf4j的示例,下面研究一下slf4j的实现,我们只关注重点代码。

slf4j的用法就是常年不变的一句"logger logger = loggerfactory.getlogger(object.class);",可见这里就是通过loggerfactory去拿slf4j提供的一个logger接口的具体实现而已,loggerfactory的getlogger的方法实现为:

?

1

2

3

4

5

6

7

8

9

10

11

12
public static logger getlogger(class<?> clazz) {

logger logger = getlogger(clazz.getname());

if (detect_logger_name_mismatch) {

class<?> autocomputedcallingclass = util.getcallingclass();

if (autocomputedcallingclass != null && nonmatchingclasses(clazz, autocomputedcallingclass)) {

util.report(string.format("detected logger name mismatch. given name: \\"%s\\"; computed name: \\"%s\\".", logger.getname(),

autocomputedcallingclass.getname()));

util.report("see " + logger_name_mismatch_url + " for an explanation");

}

}

return logger;

}

从第2行开始跟代码,一直跟到loggerfactory的bind()方法:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42
private final static void bind() {

try {

set<url> staticloggerbinderpathset = null;

// skip check under android, see also

// http://jira.qos.ch/browse/slf4j-328

if (!isandroid()) {

staticloggerbinderpathset = findpossiblestaticloggerbinderpathset();

reportmultiplebindingambiguity(staticloggerbinderpathset);

}

// the next line does the binding

staticloggerbinder.getsingleton();

initialization_state = successful_initialization;

reportactualbinding(staticloggerbinderpathset);

fixsubstituteloggers();

replayevents();

// release all resources in subst_factory

subst_factory.clear();

} catch (noclassdeffounderror ncde) {

string msg = ncde.getmessage();

if (messagecontainsorgslf4jimplstaticloggerbinder(msg)) {

initialization_state = nop_fallback_initialization;

util.report("failed to load class \\"org.slf4j.impl.staticloggerbinder\\".");

util.report("defaulting to no-operation (nop) logger implementation");

util.report("see " + no_staticloggerbinder_url + " for further details.");

} else {

failedbinding(ncde);

throw ncde;

}

} catch (java.lang.nosuchmethoderror nsme) {

string msg = nsme.getmessage();

if (msg != null && msg.contains("org.slf4j.impl.staticloggerbinder.getsingleton()")) {

initialization_state = failed_initialization;

util.report("slf4j-api 1.6.x (or later) is incompatible with this binding.");

util.report("your binding is version 1.5.5 or earlier.");

util.report("upgrade your binding to version 1.6.x.");

}

throw nsme;

} catch (exception e) {

failedbinding(e);

throw new illegalstateexception("unexpected initialization failure", e);

}

}

这个地方第7行是一个关键,看一下代码:

?

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22
static set<url> findpossiblestaticloggerbinderpathset() {

// use set instead of list in order to deal with bug #138

// linkedhashset appropriate here because it preserves insertion order

// during iteration

set<url> staticloggerbinderpathset = new linkedhashset<url>();

try {

classloader loggerfactoryclassloader = loggerfactory.class.getclassloader();

enumeration<url> paths;

if (loggerfactoryclassloader == null) {

paths = classloader.getsystemresources(static_logger_binder_path);

} else {

paths = loggerfactoryclassloader.getresources(static_logger_binder_path);

}

while (paths.hasmoreelements()) {

url path = paths.nextelement();

staticloggerbinderpathset.add(path);

}

} catch (ioexception ioe) {

util.report("error getting resources from path", ioe);

}

return staticloggerbinderpathset;

}

这个地方重点其实就是第12行的代码,getlogger的时候会去classpath下找static_logger_binder_path,static_logger_binder_path值为"org/slf4j/impl/staticloggerbinder.class",即所有slf4j的实现,在提供的jar包路径下,一定是有"org/slf4j/impl/staticloggerbinder.class"存在的,我们可以看一下:

浅谈Java日志框架slf4j作用及其实现原理

浅谈Java日志框架slf4j作用及其实现原理

浅谈Java日志框架slf4j作用及其实现原理

我们不能避免在系统中同时引入多个slf4j的实现,所以接收的地方是一个set。大家应该注意到,上部分在演示同时引入logback、slf4j-simple、log4j的时候会有警告:

浅谈Java日志框架slf4j作用及其实现原理

这就是因为有三个"org/slf4j/impl/staticloggerbinder.class"存在的原因,此时reportmultiplebindingambiguity方法控制台输出语句:

?

1

2

3

4

5

6

7

8

9
private static void reportmultiplebindingambiguity(set<url> binderpathset) {

if (isambiguousstaticloggerbinderpathset(binderpathset)) {

util.report("class path contains multiple slf4j bindings.");

for (url path : binderpathset) {

util.report("found binding in [" + path + "]");

}

util.report("see " + multiple_bindings_url + " for an explanation.");

}

}

那网友朋友可能会问,同时存在三个"org/slf4j/impl/staticloggerbinder.class"怎么办?首先确定的是这不会导致启动报错,其次在这种情况下编译期间,编译器会选择其中一个staticloggerbinder.class进行绑定。

最后staticloggerbinder就比较简单了,不同的staticloggerbinder其getloggerfactory实现不同,拿到iloggerfactory之后调用一下getlogger即拿到了具体的logger,可以使用logger进行日志输出。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持快网idc。

原文链接:http://www.cnblogs.com/xrq730/p/8619156.html

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。

快网idc优惠网 建站教程 浅谈Java日志框架slf4j作用及其实现原理 https://www.kuaiidc.com/112141.html

相关文章

发表评论
暂无评论