You can do this as follows:
To make Log4j reload your configuration file automatically when it 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 a bit of code to 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 per Tomcat boot) I start Log4j using the configureAndWatch method. Also be sure to set up a Shutdown Hook cleaning of the Log4j thread created to query the configuration file for changes (I could also have chosen to listen to the "AFTER_STOP_EVENT" from Tomcat instead).
This package is in a jar. Put it in the Tomcat classpath, and now you can set it up in your Tomcat serverl.xml.
like this:
<Server>
<Listener className="Log4JInitializer" propertiesFile="/path/to/log4j.properties"/>
</Server>