Reputation: 72676
I have an application that uses log4j to log on a text file, i have placed a log4j.properties file inside my executable jar file containing the default log configuration parameters.
My log4j.properties file looks like the following :
log4j.rootLogger=INFO, A1
log4j.appender.A1=org.apache.log4j.FileAppender
log4j.appender.A1.File=mylogfile.log
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%d{dd/MM/yyyy HH\:mm\:ss,SSS} %-5p [%t] - %m%n
My application have also a command line option that allow the user to change the log file name, so i have a function like the following that change the settings of log4j at runtime :
public void changeLogFileName(String filename) {
props.setProperty("log4j.appender.A1","org.apache.log4j.DailyRollingFileAppender");
props.setProperty("log4j.appender.A1.DatePattern","'-'ddMMyyyy");
props.setProperty("log4j.appender.A1.File",filename);
LogManager.resetConfiguration();
PropertyConfigurator.configure(props);
}
Everything work fine, unless when the statement LogManager.resetConfiguration() and/or PropertyConfigurator.configure(props) are executed a default empty log file (mylogfile.log) is automatically created. After that everything i log from my application will be written correctly in the new file, but an empty file is created anyway (with the name of the default log filename in the log4j.properties).
Is there a way to avoid the creation of the empty default log file ?
Upvotes: 4
Views: 3075
Reputation: 72676
I've finally developed log4j-additions library that allow the creation of a Lazy initialization appender that avoid the creation of the empty log file.
#Lazy File Appender
log4j.appender.A1=org.pollerosoftware.log4j.additions.appenders.LazyFileAppender
log4j.appender.A1.File=juakaritoglory.log
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%d{dd/MM/yyyy HH\:mm\:ss,SSS} %-5p [%t] - %m%n
/**
* Change the path of log file
* @param path new path
*/
public synchronized void changeLogPath(String path) {
String filename = (path.endsWith(File.separator)) ? path : path + File.separator;
filename += LOGFILENAME + "-{timestamp}.log";
props.setProperty("log4j.appender.A1","org.pollerosoftware.log4j.additions.appenders.TimestampFileAppender");
props.setProperty("log4j.appender.A1.TimestampPattern","ddMMyyyy");
props.setProperty("log4j.appender.A1.File",filename);
LogManager.resetConfiguration();
PropertyConfigurator.configure(props);
}
Upvotes: 1