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

时间:2016-02-11 17:39:01

标签: java spring-boot slf4j logback

我知道如何通过environment variablesapplication 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;
}

2 个答案:

答案 0 :(得分:5)

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

这样的事情:

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

答案 1 :(得分:1)

提供Boris the Spider提示。

首先,将一个元素 NSURL *indexURL = [NSURL URLWithString:@"https://www.google.com"]; 添加到logback.xml。

然后,这段代码将起作用:

<jmxConfigurator />

可悲的是,似乎没有更好的方法来构建对象名称:@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"); } 层次结构不可遍历,字符串“default”无法在我找到的任何地方访问。

相关问题