SLF4J
- www.slf4j.org/
- 核心依赖 slf4j-api
- 日志门面,虽然底层的日志实现变了,但原代码不必改变
slf4j-core: 日志门面
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.32</version>
</dependency>
2. 三类
- unbound
- logback 和 simple(包括 nop) 在 sl4j 时间线之后,完全遵循 sl4j 的实现
- log4j, JUL 在 sl4j 之间就出现,适配桥接技术
2.1 simple
- 自带的简单日志实现
- slf4j-simple.jar
<!-- 加上 slf4j-api 依赖-->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.7.32</version>
<scope>test</scope>
</dependency>
2.2 SLF4J bind JUL
- JUL 是 Java 原生日志框架,无需导入依赖
- 需绑定一个适配器 slf4j-jdk14
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-jdk14</artifactId>
<version>1.7.32</version>
</dependency>
2.3 SLF4J bind Log4j
- 需要绑定一个适配器 slf4j-log4j12
- log4j.jar
- log4j.properpties
<!-- 加上 slf4j-api 依赖-->
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.32</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
2.4 SLF4J bind Logback
-
jar
logback-classic, logback-core - pom.xml 因依赖传递性,只需导入 logback-classic
<!-- 加上 slf4j-api 依赖-->
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
</dependency>
2.5 SLF4J bind Log4j 2
- log4j-slf4j-impl 适配器
- slf4j借助log4j-slf4j-impl适配层,连接到log4j-api上,log4j-api再连接到log4j-core上
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-slf4j-impl</artifactId>
<version>2.17.1</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.17.1</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.17.1</version>
</dependency>
3. 示例
SLF4J: Class path contains multiple SLF4J bindings.
表明同时出现了多个日志实现,默认是先导入的先实现
import org.slf4j.LoggerFactory;
private static final Logger logger = LoggerFactory.getLogger(Demo.class);
private Logger logger = LoggerFactory.getLogger(Demo.class.getName());
// protected 子类可以直接使用
protected final Logger log = LoggerFactory.getLogger(this.getClass());
5. SLF4J 源码分析
// LoggerFactory#getLogger(java.lang.Class<?>)
Logger logger = getLogger(clazz.getName());
public static Logger getLogger(String name) {
ILoggerFactory iLoggerFactory = getILoggerFactory();
return iLoggerFactory.getLogger(name);
}
private final static void performInitialization() {
bind();
if (INITIALIZATION_STATE == SUCCESSFUL_INITIALIZATION) {
versionSanityCheck();
}
}
// org.slf4j.LoggerFactory#bind
StaticLoggerBinder.getSingleton();
网友评论