如何以编程方式设置Spring Boot的日志记录级别?

Sto*_*ica 2 java logback slf4j spring-boot

我知道如何通过环境变量应用程序属性设置日志级别.

有没有办法以编程方式设置它们?

我想为特定测试类(使用SpringJUnit4ClassRunner@SpringApplicationConfiguration)设置日志级别,但不是所有测试类都设置日志级别,并且没有针对每个组合的单独属性文件.

我尝试定义一个非懒惰的bean PropertySource来为环境添加一个新的 ; 该方法被调用,但没有效果.

@Bean
@Lazy(false)
public PropertySource testProperties(ConfigurableEnvironment environment) {
  PropertySource properties = new MapPropertySource("testProperties", Collections.singletonMap(
      "logging.level.org.springframework.security", "DEBUG"
  ));

  environment.getPropertySources().addFirst(properties);
  return properties;
}
Run Code Online (Sandbox Code Playgroud)

And*_*son 5

您可以@TestPropertySource在测试类上使用.与您尝试的基于bean的方法不同,@TestPropertySource将在上下文启动之前将属性源添加到环境中,这允许在初始化日志记录系统时拾取属性.

像这样的东西:

@RunWith(SpringJUnit4ClassRunner.class)
@SpringApplicationConfiguration(YourApplication.class)
@TestPropertySource(properties = "logging.level.org.springframework.security:DEBUG")
public class YourApplicationTests {
    // …
}
Run Code Online (Sandbox Code Playgroud)