SpringBoot日志使用
2021-03-07 本文已影响0人
GavinZZW
日志级别和格式
Spring Boot 默认已经使用了 SLF4J + LogBack . 所以我们在不进行任何额外操作
的情况下就可以使用 SLF4J + Logback 进行日志输出。
SLF4J 日志级别从小到大trace,debug,info,warn,error
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
/**
* 测试日志输出,
* SLF4J 日志级别从小到大trace,debug,info,warn,error
*
*/
@RunWith(SpringRunner.class)
@SpringBootTest
public class LogbackTest {
Logger logger = LoggerFactory.getLogger(getClass());
@Test
public void testLog() {
logger.trace("Trace 日志...");
logger.debug("Debug 日志...");
logger.info("Info 日志...");
logger.warn("Warn 日志...");
logger.error("Error 日志...");
}
}
测试结果
2020-11-16 19:58:43.094 INFO 39940 --- [ main]
com.lagou.Springboot01DemoApplicationTests : Info 日志...
2020-11-16 19:58:43.094 WARN 39940 --- [ main]
com.lagou.Springboot01DemoApplicationTests : Warn 日志...
2020-11-16 19:58:43.094 ERROR 39940 --- [ main]
com.lagou.Springboot01DemoApplicationTests : Error 日志...
由此可见 SpringBoot 默认日志级别为 INFO.
从上面的日志结合 Logback 日志格式可以知道 Spring Boot 默认日志格式是
%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n
# %d{yyyy-MM-dd HH:mm:ss.SSS} 时间
# %thread 线程名称
# %-5level 日志级别从左显示5个字符宽度
# %logger{50} 类名
# %msg%n 日志信息加换行
从springboot源码分析,在logback的base.xml和 defaults.xml中进行了如此的设置
base.xml中设置了日志级别

default.xml设置了日志格式

自定义日志输出
可以直接在配置文件编写日志相关配置
# 日志配置
# 指定具体包的日志级别 com.demo表示对哪个包生效
logging.level.com.demo=debug
# 控制台和日志文件输出格式
logging.pattern.console=%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level
%logger{50} - %msg%n
logging.pattern.file=%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50}
- %msg%n
# 日志输出路径,默认文件spring.log
logging.file.path=spring.log
#logging.file.name=log.log
日志的输出路径,可以使用 logging.file.name 或者 logging.file.path 进行定义,两者存在关系如下表。
logging.file.name | logging.file.path | 例子 | 描述 |
---|---|---|---|
(没有) | (没有) | 仅控制台记录。 | |
具体文件 | (没有) | demo.log | 写入指定的日志文件,名称可以是精确位置或相对于当前目录。 |
(没有) | 具体目录 | /demo/log | 写入 spring.log 指定的目录,名称可以是精确位置或相对于当前目录。 |
替换日志框架
Log4j 日志框架已经年久失修,原作者都觉得写的不好,所以下面演示替换日志框架为 Log4j2 的
方式。根据官网我们 Log4j2 与 logging 需要二选一

因此修改 pom如下
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<artifactId>spring-boot-starter-logging</artifactId>
<groupId>org.springframework.boot</groupId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>