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

Bittu picture Bittu · May 11, 2010 · Viewed 89.5k times · Source

I am using log4j to log information. I have used a log4j.xml file for creating log files. I have given the absolute path for each log file as a param tag value.

E.g.:

<appender name="FA" class="org.apache.log4j.DailyRollingFileAppender">
  <param name="DatePattern" value="'_'yyyyMMdd"/>
  <param name="File" value="D:/logFiles/GPreprocessor.log"/>
  <layout class="com.dnb.genericpreprocessor.common.log.AppXMLLayout"/>
</appender>

I do not want to write "GPreprocessor.log" directly. Actually, that file name is dynamic, based on my project's name. For example, if I run the program ABC.java, logging should go to D:/logFiles/ABC.log, but if I run XYZ.java, logging should go to D:/logFiles/XYZ.log. The file's location will always remain the same: D:/logFiles/. How can I change the log file's name dynamically?

Answer

Big B picture Big B · Jul 2, 2011

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).