Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 759
Bittu Avatar asked May 11 '10 13:05

Bittu


People also ask

How do you give a dynamic file name in the Appender in Log4j2 XML?

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

How do you set log file path in log4j properties dynamically?

System. setProperty("{my. log", "C:/logfile. log");

What is Appender name in log4j?

The appender FILE is defined as org. apache. log4j.

What is log4j Appender file file?

The log4j. properties file is a log4j configuration file which stores properties in key-value pairs. The log4j properties file contains the entire runtime configuration used by log4j. This file will contain log4j appenders information, log level information and output file names for file appenders.


1 Answers

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

like image 188
Big B Avatar answered Oct 01 '22 00:10

Big B