Skip to content

Provide a programmatic way to enable/disable log4j2 JMX beans creation #2462

@sdavids

Description

@sdavids

JUnit 5 - Disable Log4J JMX beans creation in tests

Spring Boot - Do not create log4j2 JMX beans if spring.jmx.enabled=false

Log4j - Enabling JMX

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.

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.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions