Thursday, September 4, 2014

Log4j watchdog to monitor changes in log4j properties file

In running systems in production sometimes there is a need to change the log levels to see the details of what is happening inside the application. There might be a buggy situation and to get more insight, it is needed to do that. However you do not want to restart the application as the situation might be transient. 

Usually most Java based systems use log4j for logging. To get more insight at real time, there comes the need to change the log level configured in log4j.properties file.

For that log4j comes up with a class which can help in watching the changes in log4j.properties file and reload the log4j system, if log levels are changed. The following line of code starts a thread which keeps monitoring the log4j.properties file

PropertyConfigurator.configureAndWatch(<Path to log4j.properties file>,  <delay to monitor>);

delay to monitor -  the time interval in milliseconds in which the watchdog checks the log4j properties file for modification.

If you are in a web application environment, you can do this in a Listener class. Listener classes are called when the application comes up and they can set the watch dog on log4j properties file. In your application, make sure to call the above line only once preferably at start up, as each call will lead to a watch dog thread being spawned.

In Spring enabling watchdog

If you are in Spring based environment, then Spring provides a listener which enables the watch dog to monitor the changes in log4j.properties file.

The following code needs to be put in web.xml to enable the watching.

<!--  Location of log4j file -->
<context-param>
<param-name>
      log4jConfigLocation
  </param-name>
<param-value>
      classpath:log4j.properties
  </param-value>
</context-param>

<!-- Interval in which the log file will be watched for changes.
     The time is in millisecond
 -->
<context-param>
<param-name>
    log4jRefreshInterval
 </param-name>
<param-value>
    300000
 </param-value>
</context-param>


<!-- Watch dog for log4j file --> <listener> <listener-class>
org.springframework.web.util.Log4jConfigListener
</listener-class> </listener>
For an example of a web application using Spring configurer see Sample Web application using Spring Watchdog to watch log4j

Tutorials on Spring

No comments:

Post a Comment