Tuesday, November 21, 2006

Changing log4j properties at run time

I had a requirement where the log4j property file generated should have a unique id appended to it. This id is generated inside the running application. One simple way of doing it is: Make use of system variables inside the log4j properties file:
log4j.appender.R.File=
d:/mylogs/servicelogger[%d{MYAPPENDER}].log
After you have done this, make sure you set MYAPPENDER in the system environment.

Another way of doing this is: read the log4j properties inside the application, locate the specific property(in our case: log4j.appender.R.File). Change this property and instantiate log4j using this new set of properties. Here is the code to do this:
prop.load(new FileInputStream(logPropertyFile));
String userLogFName = (String)prop.getProperty("log4j.appender.R.File");
prop.remove("log4j.appender.R.File");
prop.setProperty("log4j.appender.R.File", newFName);
org.apache.log4j.PropertyConfigurator.configure(prop);
this.serviceLogger = new
Log4JLogger(org.apache.log4j.Logger.getLogger(DTM_LOG4J_CATEGORY_NAME));

0 Comments:

Post a Comment

<< Home