转:slf4j-api、slf4j-log4j12、log4j之间关系

时间:2023-03-09 16:39:33
转:slf4j-api、slf4j-log4j12、log4j之间关系

1. slf4j-api

slf4j:Simple Logging Facade for Java,为java提供的简单日志Facade。Facade门面,更底层一点说就是接口。它允许用户以自己的喜好,在工程中通过slf4j接入不同的日志系统。

因此slf4j入口就是众多接口的集合,它不负责具体的日志实现,只在编译时负责寻找合适的日志系统进行绑定。具体有哪些接口,全部都定义在slf4j-api中。查看slf4j-api源码就可以发现,里面除了public final class LoggerFactory类之外,都是接口定义。因此slf4j-api本质就是一个接口定义。

它只提供一个核心slf4j api(就是slf4j-api.jar包),这个包只有日志的接口,并没有实现,所以如果要使用就得再给它提供一个实现了些接口的日志包,比 如:log4j,common logging,jdk log日志实现包等,但是这些日志实现又不能通过接口直接调用,实现上他们根本就和slf4j-api不一致,因此slf4j又增加了一层来转换各日志实 现包的使用,比如slf4j-log4j12等。

slf4j+log4j组合使用模式:
1. slf4j-api-1.5.11.jar
2. slf4j-log4j12-1.5.11.jar
3. log4j-1.2.15.jar
4. log4j.properties(也可以是 log4j.xml)

具体使用日志类的API:

1. log4j:
import org.apache.log4j.Logger;
Logger logger= Logger.getLogger(xx.class);
2. slf4j+log4j:(推荐)
import  org.slf4j.Logger;
import org.slf4j.LoggerFactory;
Logger logger = LoggerFactory.getLogger(xx.class);

2. slf4j-api、slf4j-log4j12、log4j

下图比较清晰的描述了它们之间的关系,例子为当系统采用log4j作为日志框架实现的调用关系:

转:slf4j-api、slf4j-log4j12、log4j之间关系

1. 首先系统包含slf4j-api作为日志接入的接口:编译时slf4j-api中public final class LoggerFactor类中private final static void bind()方法会寻找具体的日志实现类绑定,主要通过StaticLoggerBinder.getSingleton()的语句调用。
2. slf4j-log4j12是链接slf4j-api和log4j中间的适配器:它实现了slf4j-api中StaticLoggerBinder接口,从而使得在编译时绑定的是slf4j-log4j12的getSingleton()方法。
3. log4j是具体的日志系统:通过slf4j-log4j12初始化Log4j,达到最终日志的输出。

Failed to load class org.slf4j.impl.StaticLoggerBinder

This warning message is reported when the org.slf4j.impl.StaticLoggerBinder class could not be loaded into memory. This happens when no appropriate SLF4J binding could be found on the class path. Placing one (and only one) of slf4j-nop.jar slf4j-simple.jarslf4j-log4j12.jarslf4j-jdk14.jar or logback-classic.jar on the class path should solve the problem.

SINCE 1.6.0 As of SLF4J version 1.6, in the absence of a binding, SLF4J will default to a no-operation (NOP) logger implementation.

If you are responsible for packaging an application and do not care about logging, then placing slf4j-nop.jar on the class path of your application will get rid of this warning message. Note that embedded components such as libraries or frameworks should not declare a dependency on any SLF4J binding but only depend on slf4j-api. When a library declares a compile-time dependency on a SLF4J binding, it imposes that binding on the end-user, thus negating SLF4J's purpose.

意思就是说,解决这个bug需要添加以下任意一个依赖

  • slf4j-nop.jar
  • slf4j-simple.jar
  • slf4j-log4j12.jar
  • slf4j-jdk14.jar
  • logback-classic.jar

原文:https://www.slf4j.org/codes.html#StaticLoggerBinder