日志框架
简单画一个日志框架,参考我的雨雀笔记
Springboot日志框架
快速入门
创建 springboot web 项目,使用 springboot 2.7
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.0</version>
<relativePath/>
</parent>
...
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
</dependencies>
(图来自互联网,侵删)
默认提供两个日志门面(门面,可理解为一套接口,一套规范)
- slf4j(对应 slf4j-api.jar)
- log4j2(对应 log4j-api.jar )
默认使用的日志实现是 logback
添加 logback.xml
<?xml version="1.0" encoding="UTF-8" ?>
<configuration>
<property name="pattern"
value="%d{yyyy-MM-dd HH:mm:ss.SSS} [%-5level] [%thread] %c.%M Line:%L %m%n"/>
<!--console appender-->
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
<target>System.in</target>
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<pattern>${pattern}</pattern>
</encoder>
</appender>
<root level="debug">
<appender-ref ref="console"/>
</root>
</configuration>
测试类:使用 sl4j2 和 log4j2 门面记录日志
import org.apache.logging.log4j.LogManager;
import org.slf4j.LoggerFactory;
@SpringBootTest
public class T1 {
@Test
public void te1() {
//使用 slf4j 门面(slf4j2 --> logback)
org.slf4j.Logger logger_slf4j = LoggerFactory.getLogger(T1.class);
logger_slf4j.debug("debug");
//使用 log4j2 门面(log4j2 --> log4j-to-slf4j --> slf4j --> logback)
org.apache.logging.log4j.Logger logger_log4j2 = LogManager.getLogger(T1.class);
logger_log4j2.debug("debug");
}
}
原理
图中的 1
即为 log4j-to-slf4j-2.x.jar
,是一个适配器,见 https://logging.apache.org/log4j/2.x/log4j-to-slf4j/index.html
切换日志实现(log4j2)
排除 spring-boot-starter-logging
,添加 spring-boot-starter-log4j2
依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
日志配置:log4j2.xml
<?xml version="1.0" encoding="UTF-8" ?>
<Configuration status="info" monitorInterval="5">
<Appenders>
<Console name="console">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%-5level] [%t] %c{36}:%L >>>> %m%n"/>
</Console>
</Appenders>
<Loggers>
<Root level="info">
<AppenderRef ref="console"/>
</Root>
</Loggers>
</Configuration>
测试
@SpringBootTest
public class T2 {
@Test
public void t() {
org.slf4j.Logger LOGGER = LoggerFactory.getLogger(T1.class);
LOGGER.error("error");
LOGGER.warn("warn");
LOGGER.info("info");
LOGGER.debug("debug");
LOGGER.trace("trace");
Logger logger = LogManager.getLogger(T2.class);
logger.info("logger by log4j2");
}
}
原理
图中的 2 是 log4j-slf4j-impl.x.jar
,是一个绑定器,详情见 https://logging.apache.org/log4j/2.x/log4j-slf4j-impl/index.html