How to give dynamic file name in the appender in log4j.xml

It’s much easier to do the following:

In log4j.xml define variable as ${variable}:

<appender name="FILE" class="org.apache.log4j.FileAppender">    
    <param name="File" value="${logfilename}.log" />
    <layout class="org.apache.log4j.PatternLayout">
        <param name="ConversionPattern" value="%d::[%t]::%-5p::%c::%x - %m%n" />
    </layout>       
</appender>

Then make sure you set the system property when you start your JVM such as:

java -Dlogfilename=my_fancy_filename  example.Application

That will create a dynamic log file name: my_fancy_filename.log

Alternatively, you can set the system property in code so long as you do it before you create a logger (this is useful if you want your PID in your logs for instance). Such as:

System.setProperty("logfilename", "a_cool_logname");

Once that is set you can go ahead and get your loggers as normal and they will log to the dynamic file (be careful of those static Loggers that create loggers before your main method executes).

Leave a Comment