Search code examples
springloggingspring-testlog-level

How set log level without @springboottest?


I decided to write a "component" test without "@SpringBootTest". Faced the problem that some settings in application.yml do not work.

I try to change the level of logging - does not work. What am I doing wrong?

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. I understand that my question can be trivial, but before I asked it, I looked at a lot of information both in Google and on the Stack. P.S.S Don't use @SpringBootTest


Solution

  • Spring Test doesn't govern by application level logging settings. You should place a separate logback configuration file under ../test/resources/

    In 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>
    

    Btw, also it's needed to specify full package in your yml like:

    logging:
      level:
        org.springframework.web: INFO