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

How to set Spring Boot's logging levels programmatically?

我知道如何通过 and application properties 设置日志级别。

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

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

我试过了defining a non-lazy bean to add a new PropertySource to the environment;调用了该方法,但没有任何效果。

@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;
}

提示归功于 Boris the Spider

首先,添加一个元素<jmxConfigurator />到logback.xml。

然后,此代码将起作用:

@Before
public void configureLogging() throws JMException {
    ObjectName name = new ObjectName(String.format("ch.qos.logback.classic:Name=default,Type=%s", JMXConfigurator.class.getName()));
    JMXConfiguratorMBean logbackMBean = JMX.newMBeanProxy(ManagementFactory.getPlatformMBeanServer(), name, JMXConfiguratorMBean.class);
    logbackMBean.setLoggerLevel("org.springframework.security", "DEBUG");
}

遗憾的是,似乎没有更好的方法来构建对象名称:Package 层次结构不可遍历,字符串 "default" 在我能找到的任何地方都无法访问.

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

像这样:

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