Change Log4j Logging Level at Runtime Using JMX/Spring

Monitoring application servers is a daunting task. Without the right instrumentation of your code it is even impossible. I try to use log4j as much as possible and in general I’m very generous regarding logging levels. But occasionally the console just gets flooded with logging output. Typically then I would modify the logging configuration files and restart the server which may be very time consuming and unnecessary.

In the past I had used JMX to switch logging levels at runtime for various projects. The first time now I have tried this with the Spring framework and it worked like a charm (did you expect anything else). I’m making the solution public in case I need this for future projects and to document the steps required!

First, a bean is required that uses the logging API (here log4j) to manage the logging level.

It’s been annotated with Spring JMX annotations to provide JMX meta data. Next, we need to export the bean as a JMX Bean. This is supported very well by the Springframework’s MBeanExporter.

12345678910111213141516171819202122232425

<?xml version="1.0" encoding="UTF-8"?><beansxmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"><beanid="exporter"class="org.springframework.jmx.export.MBeanExporter"><propertyname="assembler"ref="assembler"/><propertyname="namingStrategy"ref="namingStrategy"/><propertyname="autodetect"value="true"/></bean><beanid="jmxAttributeSource"class="org.springframework.jmx.export.annotation.AnnotationJmxAttributeSource"/><!-- will create management interface using annotation metadata --><beanid="assembler"class="org.springframework.jmx.export.assembler.MetadataMBeanInfoAssembler"><propertyname="attributeSource"ref="jmxAttributeSource"/></bean><!-- will pick up the ObjectName from the annotation --><beanid="namingStrategy"class="org.springframework.jmx.export.naming.MetadataNamingStrategy"><propertyname="attributeSource"ref="jmxAttributeSource"/></bean><beanid="log4jConfig"class="at.martinahrer.blueprint.log4j.Logging"></bean></beans>

Finally to connect to the MBeanServer using jconsole the JVM (running the MBean) must be started with the system property -Dcom.sun.management.jmxremote set.