Java – changing the log4j properties file at run time will result in the creation of an empty default log

I have an application that uses log4j to log in to a text file, and I put a log4j. Net in my executable jar file Properties file, which contains the default log configuration parameters

My log4j The properties file is as follows:

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 also has a command line option that allows users to change the log file name, so I have a function like the following to change the setting of log4j at run time:

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 is normal unless you execute the logmanager statement Resetconfiguration() and / or propertyconfigurator A default empty log file (mylogfile. Log) is automatically created when configure (props) After that, everything I record in the application will be written correctly in the new file, but an empty file will be created anyway (using the name of the default log file name in log4j.properties)

Is there any way to avoid creating an empty default log file?

Solution

I finally developed the log4j additions library, which allows you to create a lazy initialization appender to avoid creating empty log files

log4. properties

#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

Method of changing path

/**
 * 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);
}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>