如何在没有@springboottest的情况下设置日志级别?

时间:2018-02-20 10:20:26

标签: spring logging spring-test log-level

我决定在没有“@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

P.S。我理解我的问题可能很简单,但在我提出这个问题之前,我在Google和堆栈中查看了很多信息。 P.S.S不要使用@SpringBootTest

1 个答案:

答案 0 :(得分:-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