Java 如何设置弹簧靴';以编程方式设置日志记录级别?

Java 如何设置弹簧靴';以编程方式设置日志记录级别?,java,spring-boot,slf4j,logback,Java,Spring Boot,Slf4j,Logback,我知道如何通过和设置日志级别 有没有办法以编程方式设置它们 我想为特定的测试类(使用SpringJUnit4ClassRunner和@SpringApplicationConfiguration)设置日志级别,但不是所有测试类,并且没有针对每个组合的单独属性文件 我试过了;调用了该方法,但没有任何效果 @Bean @Lazy(false) public PropertySource testProperties(ConfigurableEnvironment environment) { P

我知道如何通过和设置日志级别

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

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

我试过了;调用了该方法,但没有任何效果

@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;
}
这些提示值得称赞

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

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

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

大概是这样的:

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

我所知道的在启动记录器后配置日志级别的唯一方法是通过JMX…@boristesspider,它只适用于
java.util.logging
,spring boot不使用它。这两种方法都不正确-Logback和Log4j2都支持JMX,如果您希望,spring boot支持JUL(但为什么您会…)。您只需要在配置文件中配置JMX连接器。你不会说你把Boot插入了哪个框架。宾果。虽然我希望有一种方法可以在上下文启动之前更改属性。@BoristheSpider我确实说过,但是通过标签。我真的应该首先想到其中一个:这对我来说不起作用,我正在创建一个springboot库,它没有主springboot应用程序,因此所有内容都必须从测试类加载。不知何故,我无法禁用/更改日志记录