It is possible to do as follows:
To make Log4j reload your configuration file automatically when it undergoes changes, you can do this with the configureAndWatch method. But the default boot procedure does not use configureAndWatch (if you just put the .properties file in the classpath). That way you can write little code for Log4j to do this. The solution I found was the implementation of a Tomcat Lifecyclelistener.
import org.apache.catalina.Lifecycle;
import org.apache.catalina.LifecycleEvent;
import org.apache.catalina.LifecycleListener;
import org.apache.log4j.LogManager;
import org.apache.log4j.PropertyConfigurator;
public class Log4JInitializer implements LifecycleListener
{
private String propertiesFile;
public String getPropertiesFile()
{
return this.propertiesFile;
}
public void setPropertiesFile(String propertiesFile)
{
this.propertiesFile = propertiesFile;
}
@Override
public void lifecycleEvent(LifecycleEvent event)
{
if (Lifecycle.BEFORE_START_EVENT.equals(event.getType()))
initializeLog4j();
}
private void initializeLog4j()
{
//Log4j monitora o arquivo para mudanças
PropertyConfigurator.configureAndWatch(propertiesFile);
// shutdown log4j (e na thread monitor) no shutdown
Runtime.getRuntime().addShutdownHook(new Thread()
{
@Override
public void run()
{
LogManager.shutdown();
}
});
}
}
EDIT
monitor "BEFORE_START_EVENT", and when this happens (which is once by Tomcat booting) I boot Log4j using the configureAndWatch method. Also don’t forget to set up a clean Shutdown Hook Log4j thread created to query the configuration file for changes (I could also have chosen to listen to Tomcat’s "AFTER_STOP_EVENT" instead).
This package is in a jar. Put it in the Tomcat classpath, and now you can configure it in your Tomcat serverl.xml.
thus:
<Server>
<Listener className="Log4JInitializer" propertiesFile="/path/to/log4j.properties"/>
</Server>
It is a difficult problem to diagnose the distance, but do the following test: (1) start the Tomcat and the application, (2) generate some logs, (3) stop the application (stop) keeping the Tomcat running and finally (4) see if the log file can be deleted (deleted from disk). My suspicion is that there may be some static log reference that is not being finalized.
– utluiz
Yes, it may well be a classloader Leak. log4j.properties is usually loaded by classloader.
– elias
I agree with @Elias . Tomcat’s Log4j must be conflicting with your application’s log4j.
– rdllopes