-
-
Notifications
You must be signed in to change notification settings - Fork 1.7k
Description
JUnit 5 - Disable Log4J JMX beans creation in tests
Spring Boot - Do not create log4j2 JMX beans if spring.jmx.enabled=false
JMX support is enabled by default [...] To disable JMX completely, and prevent these MBeans from being created, specify system property log4j2.disableJmx to true when you start the Java VM.
logging-log4j2/log4j-core/src/main/java/org/apache/logging/log4j/core/jmx/Server.java
Lines 129 to 131 in 7b5d23e
private static boolean isJmxDisabled() { | |
return PropertiesUtil.getProperties().getBooleanProperty(PROPERTY_DISABLE_JMX); | |
} |
For almost all tests the creation of the log4j2 JMX beans is unnecessary.
Spring Boot has disabled their JMX beans creation by default. @SpringBootTest
will create log4j2 JMX beans if one uses log4j2 as its logging backend:
configurations {
implementation {
exclude(module = "spring-boot-starter-logging")
}
}
dependencies {
implementation("org.springframework.boot:spring-boot-starter")
implementation("org.springframework.boot:spring-boot-starter-log4j2")
testImplementation("org.springframework.boot:spring-boot-starter-test")
}
package com.example.demo;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.jmx.support.MBeanServerFactoryBean;
import static org.assertj.core.api.Assertions.assertThat;
@SpringBootTest
class DemoApplicationTests {
@Test
void contextLoads() {
var factory = new MBeanServerFactoryBean();
factory.setLocateExistingServerIfPossible(true);
factory.afterPropertiesSet();
var server = factory.getObject();
assertThat(server.getDomains()).doesNotContain("org.apache.logging.log4j2"); // fails
}
}
Ideally, the creation of the log4j JMX beans would be opt-in but I guess for backward compatibility reasons the default cannot be changed.
It is easy to forget to set the log4j2.disableJmx
system property—I would wager most people are not even aware of it.
I suggest adding a programmatic way of enabling/disabling the log4j2 JMX bean creation.
Spring Boot could auto-configure it depending on spring.jmx.enabled
.
JUnit5 could disable it by default.
Explicitly setting log4j2.disableJmx
would override the programmatic enabling/disabling.