1. 概述

在本教程中,我们将学习如何在运行 Spring Boot 应用的测试时设置日志级别

当测试通过时,我们通常可以忽略日志输出。但一旦测试失败,合适的日志级别就成了诊断问题的关键工具。本文将介绍几种在测试期间控制日志输出的方法。


2. 日志级别的重要性

合理配置日志级别能大幅节省排查问题的时间。

比如,如果测试在 CI 服务器上失败,但在本地开发环境能正常运行,没有足够的日志输出,我们几乎无法定位问题。相反,日志输出过多,又会淹没关键信息,增加排查难度。

我们可以通过精细控制不同包的日志级别来达到平衡。例如,对关键业务逻辑包设置较低的日志级别(如 DEBUG),对依赖库或非关键模块设置较高日志级别(如 INFOERROR)。


3. 在 application.properties 中配置日志级别

如果我们希望在测试中调整日志级别,可以在 src/test/resources/application.properties 中添加如下配置:

logging.level.com.baeldung.testloglevel=DEBUG

这行配置将为 com.baeldung.testloglevel 包设置日志级别为 DEBUG

我们也可以设置全局日志级别(即 root 日志级别):

logging.level.root=INFO

✅ 示例:添加一个写日志的接口

为了验证配置是否生效,我们可以添加一个简单的 REST 接口:

@RestController
public class TestLogLevelController {

    private static final Logger LOG = LoggerFactory.getLogger(TestLogLevelController.class);

    @Autowired
    private OtherComponent otherComponent;

    @GetMapping("/testLogLevel")
    public String testLogLevel() {
        LOG.trace("This is a TRACE log");
        LOG.debug("This is a DEBUG log");
        LOG.info("This is an INFO log");
        LOG.error("This is an ERROR log");

        otherComponent.processData();

        return "Added some log output to console...";
    }
}

当我们调用这个接口时,如果配置正确,就能看到 DEBUG 级别的日志输出:

2019-04-01 14:08:27.545 DEBUG 56585 --- [nio-8080-exec-1] c.b.testloglevel.TestLogLevelController  : This is a DEBUG log
2019-04-01 14:08:27.545  INFO 56585 --- [nio-8080-exec-1] c.b.testloglevel.TestLogLevelController  : This is an INFO log
2019-04-01 14:08:27.546 ERROR 56585 --- [nio-8080-exec-1] c.b.testloglevel.TestLogLevelController  : This is an ERROR log
2019-04-01 14:08:27.546  INFO 56585 --- [nio-8080-exec-1] c.b.component.OtherComponent  : This is an INFO log from another package
2019-04-01 14:08:27.546 ERROR 56585 --- [nio-8080-exec-1] c.b.component.OtherComponent  : This is an ERROR log from another package

⚠️ 这种方式非常简单,适用于使用 @SpringBootTest 注解的测试。但如果测试不依赖 Spring 上下文,则需要其他方式配置。


3.1. 基于 Profile 的日志配置

虽然将配置写入 application.properties 已能满足大多数场景,但有时我们需要为特定测试或测试组设置不同的日志级别

此时,可以使用 @ActiveProfiles 注解为测试类指定一个 profile:

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT, classes = TestLogLevelApplication.class)
@EnableAutoConfiguration(exclude = SecurityAutoConfiguration.class)
@ActiveProfiles("logging-test")
public class TestLogLevelWithProfileIntegrationTest {
    // ...
}

然后在 src/test/resources 下创建 application-logging-test.properties 文件:

logging.level.com.baeldung.testloglevel=TRACE
logging.level.root=ERROR

这样,我们就可以在不同测试中使用不同日志级别,避免相互干扰。


4. 使用 Logback 配置日志级别

Spring Boot 默认使用 Logback 作为日志框架。我们也可以直接在 src/test/resources 下添加 logback-test.xml 文件来自定义日志行为:

<configuration>
    <include resource="/org/springframework/boot/logging/logback/base.xml"/>
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>
    <root level="error">
        <appender-ref ref="STDOUT"/>
    </root>
    <logger name="com.baeldung.testloglevel" level="debug"/>
</configuration>

这个配置将:

  • 设置全局日志级别为 ERROR
  • com.baeldung.testloglevel 包的日志级别设为 DEBUG

验证日志输出:

2019-04-01 14:08:27.545 DEBUG 56585 --- [nio-8080-exec-1] c.b.testloglevel.TestLogLevelController  : This is a DEBUG log
2019-04-01 14:08:27.545  INFO 56585 --- [nio-8080-exec-1] c.b.testloglevel.TestLogLevelController  : This is an INFO log
2019-04-01 14:08:27.546 ERROR 56585 --- [nio-8080-exec-1] c.b.testloglevel.TestLogLevelController  : This is an ERROR log
2019-04-01 14:08:27.546  INFO 56585 --- [nio-8080-exec-1] c.b.component.OtherComponent  : This is an INFO log from another package
2019-04-01 14:08:27.546 ERROR 56585 --- [nio-8080-exec-1] c.b.component.OtherComponent  : This is an ERROR log from another package

4.1. Profile-based Logback 配置

我们还可以通过 springProfile 标签在同一个 logback.xml 文件中定义多个 profile:

<configuration>
    <include resource="/org/springframework/boot/logging/logback/base.xml"/>
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
        </encoder>
    </appender>
    <root level="error">
        <appender-ref ref="STDOUT"/>
    </root>
    <springProfile name="logback-test1">
        <logger name="com.baeldung.testloglevel" level="info"/>
    </springProfile>
    <springProfile name="logback-test2">
        <logger name="com.baeldung.testloglevel" level="trace"/>
    </springProfile>
</configuration>

在测试中切换 profile(如 logback-test1logback-test2)即可看到对应级别的日志输出。


5. Log4J 替代方案

如果你使用的是 Log4J2,可以在 src/test/resources 下添加 log4j2-spring.xml 文件进行配置:

<Configuration>
    <Appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout
                pattern="%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n" />
        </Console>
    </Appenders>

    <Loggers>
        <Logger name="com.baeldung.testloglevel" level="debug" />

        <Root level="info">
            <AppenderRef ref="Console" />
        </Root>
    </Loggers>
</Configuration>

也可以通过 application.properties 指定配置文件路径:

logging.config=classpath:log4j-testloglevel.xml

验证输出:

2019-04-01 14:08:27.545 DEBUG 56585 --- [nio-8080-exec-1] c.b.testloglevel.TestLogLevelController  : This is a DEBUG log
2019-04-01 14:08:27.545  INFO 56585 --- [nio-8080-exec-1] c.b.testloglevel.TestLogLevelController  : This is an INFO log
2019-04-01 14:08:27.546 ERROR 56585 --- [nio-8080-exec-1] c.b.testloglevel.TestLogLevelController  : This is an ERROR log
2019-04-01 14:08:27.546  INFO 56585 --- [nio-8080-exec-1] c.b.component.OtherComponent  : This is an INFO log from another package
2019-04-01 14:08:27.546 ERROR 56585 --- [nio-8080-exec-1] c.b.component.OtherComponent  : This is an ERROR log from another package

6. 小结

本文介绍了在 Spring Boot 测试中设置日志级别的多种方式:

方法 适用场景 优点 缺点
application.properties 快速配置全局日志级别 简单易用 无法灵活控制 profile
@ActiveProfiles + application-{profile}.properties 多测试场景 灵活 需要多个配置文件
logback-test.xml 精细控制日志输出 功能强大 配置较复杂
logback.xml + <springProfile> profile-based 日志配置 统一管理 配置较复杂
log4j2-spring.xml 使用 Log4J2 的项目 支持 Log4J2 需额外依赖

✅ **推荐优先使用 application.propertieslogback-test.xml**,前者适合快速配置,后者适合需要精细控制的场景。

完整示例代码可在 GitHub 获取。


原始标题:Setting the Log Level in Spring Boot When Testing | Baeldung