Saturday, February 20, 2010

Change the log file name dynamically using system properties

Recently I wanted the start multiple number of server instances using the same configuration so when I start nodes of the same server i should be having different log files for each instance starting in different location. So can be done very easy without writing a new appender or doing anything just configuring your log4j.properties file.

provide your log file name like this
log4j.appender.CARBON_LOGFILE.File=repository/logs/${instance.log}/wso2carbon${instance.log}.log

This is really nicely works due to few reasons. Once you set the log4j.properties file like this you can give set a system property for each instance you are starting with the name of "instance.log" and that will be picked before creating the log file and it will create the log file in the given location.

Ex: if you set the value of system property "instance.log" as "Instance1" it will create the log in location repository/logs/Instance1/wso2carbonInstance1.log.

This file name appending works very nicely and in normal scenarios you are not setting any system property and this will create the logs in the default location which is like this : repository/logs/wso2carbon.log. This appending is working very smoothly so you can append anything for the file name or to the directory name and and if you do not set the system property it will simply ignore that.

To get dynamic log files you do not have to write any code other than setting system property and change the log4j.properties files.

1 comment :

Valerie said...

That worked for me, and I had been previously unsuccessful with attempts to do this in java code directly. Using the command line was quick and easy.

I added
-Dlog4j.suffix=blah
to my java command line after including ${log4j.suffix} in my log4j file path.

Thanks!