默认使用slf4j + logback 进行实现

1
2
3
4
<dependency>
<artifactId>spring-boot-starter-logging</artifactId>
<groupId>org.springframework.boot</groupId>
</dependency>

快速入门

直接使用spring配置

1
2
3
4
5
6
7
8
9
10
11
12
logging.level.cn.quguai = debug

logging.pattern.console=[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%p] %c -%m%n
logging.pattern.file=[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%p] %c -%m%n

# 两者只能留下一个path默认文件名是spring.log
#logging.file.name=./logs/springboot.log
logging.file.path=./logs

logging.logback.rollingpolicy.file-name-pattern=${logging.file.path}/roll_logback.%d{yyyy-MM-dd-HH-mm-ss}.log%i.zip
logging.logback.rollingpolicy.max-file-size=1KB
logging.logback.rollingpolicy.max-history=30
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
@SpringBootTest
class SpringBootLogApplicationTests {

private static final Logger logger = LoggerFactory.getLogger(SpringBootLogApplicationTests.class);

@Test
void contextLoads() {
logger.info("info"); // 默认级别
logger.debug("debug");

// 即使桥接器的形式使用log4j2的门面输出,默认还是会转为slf4j+logback
org.apache.logging.log4j.Logger logger = LogManager.getLogger(SpringBootLogApplicationTests.class);
logger.info("info log4j2");
logger.debug("debug log4j2");
}
}

指定配置

给类路径下放上每个日志框架自己的配置文件;SpringBoot就不使用默认配置的了

日志框架 配置文件
Logback logback-spring.xml, logback.xml
Log4j2 log4j2-spring.xml , log4j2.xml
JUL logging.properties

使用SpringBoot解析日志配置

logback-spring.xml:由SpringBoot解析日志配置。

1
2
3
4
5
6
7
8
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<springProfile name="default">
<pattern>${pattern}</pattern>
</springProfile>
<springProfile name="test">
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %c{36} ==== %msg%n</pattern>
</springProfile>
</encoder>
1
spring.profiles.active=test

日志切换到log4j2

image.png

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion> <== 排除logging依赖:logback依赖
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId> <== 引入log4j2的依赖,底层依然使用slf4j
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>

image.png