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?
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).
System. setProperty("{my. log", "C:/logfile. log");
The appender FILE is defined as org. apache. log4j.
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.
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With