【问题标题】:How set log level without @springboottest?如何在没有@springboottest 的情况下设置日志级别?
【发布时间】:2018-02-20 10:20:25
【问题描述】:

我决定编写一个没有“@SpringBootTest”的“组件”测试。面临application.yml部分设置不起作用的问题。

我尝试更改日志记录级别 - 不起作用。我做错了什么?

TestdemoApplicationTests

@RunWith(SpringRunner.class)
@EnableConfigurationProperties
@ContextConfiguration(classes = TestConf.class, initializers = TestContextInitializer.class)
public class TestdemoApplicationTests {

    @Test
    public void logLevel() {

    }

}

TestConf

@Configuration
public class TestConf {
}

TestContextInitializer

public class TestContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {
    @Override
    public void initialize(ConfigurableApplicationContext applicationContext) {
        try {
            Resource resource = applicationContext.getResource("classpath:application.yml");
            YamlPropertySourceLoader sourceLoader = new YamlPropertySourceLoader();
            PropertySource<?> yamlTestProperties = sourceLoader.load("applicationProperties", resource, null);
            applicationContext.getEnvironment().getPropertySources().addFirst(yamlTestProperties);
            String[] profiles = applicationContext.getEnvironment().getProperty("spring.profiles.active").replaceAll(" ", "").split(",");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}

application.yml

spring:
  profiles:
    active: junit

logging:
  level:
    ROOT: INFO
    springframework.web: INFO
    hibernate: INFO

Look at my Screenshot (Expected log level is info, but actual is debug

附:我知道我的问题可能是微不足道的,但在我提出这个问题之前,我在 Google 和 Stack 上查看了很多信息。 P.S.S 不要使用@SpringBootTest

【问题讨论】:

  • 这些属性由 Spring Boot 处理,因为您选择不使用它,这些功能显然不起作用。

标签: spring logging spring-test log-level


【解决方案1】:

Spring Test 不受应用程序级别日志记录设置的约束。 您应该在 ../test/resources/ 下放置一个单独的 logback 配置文件

在 XML 中:

 <?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <include resource="org/springframework/boot/logging/logback/base.xml" />
    <logger name="org.springframework" level="INFO"/>
</configuration>

顺便说一句,还需要在您的 yml 中指定完整的包,例如:

logging:
  level:
    org.springframework.web: INFO

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-05-11
    • 2018-07-18
    • 1970-01-01
    • 2023-02-15
    • 1970-01-01
    • 2018-06-27
    • 2012-05-04
    • 2017-10-01
    相关资源
    最近更新 更多