【问题标题】:How to set Spring Boot's logging levels programmatically?如何以编程方式设置 Spring Boot 的日志记录级别?
【发布时间】:2016-05-22 15:22:13
【问题描述】:

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

【问题讨论】:

  • 记录器启动后,我知道配置日志级别的唯一方法是通过 JMX...
  • @BoristheSpider 仅适用于 java.util.logging,spring-boot 不使用。
  • 在这两个方面都不是真的——Logback 和 Log4j2 都支持 JMX,如果你想要的话,Spring Boot 支持 JUL(但你为什么要......)。您只需要在配置文件中配置 JMX 连接器。你没有说你把 Boot 插入了哪个框架。
  • 宾果游戏。虽然我希望有一种方法可以在上下文启动之前更改属性。
  • @BoristheSpider 我确实说过,但通过标签。

标签: java spring-boot slf4j logback


【解决方案1】:

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

类似这样的:

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

【讨论】:

  • 这对我不起作用,我正在创建一个没有主 springboot 应用程序的 spring boot 库,因此必须从测试类加载所有内容。不知何故我无法禁用/更改日志记录
【解决方案2】:

感谢Boris the Spider 的提示。

首先,在 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");
}

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

【讨论】:

猜你喜欢
  • 2013-12-27
  • 2016-02-17
  • 1970-01-01
  • 2010-10-17
  • 1970-01-01
  • 2014-02-17
  • 2018-05-15
  • 2014-08-25
相关资源
最近更新 更多