How do I make log4j clear a log at startup?

2020-02-02 10:57发布

问题:

I want the log to roll over as long as the application is running, but I want the log to start fresh when the application is restarted.

Updated: Based on erickson's feedback, my appender looks like this:

   <appender name="myRFA" class="org.apache.log4j.RollingFileAppender">
      <param name="File" value="my-server.log"/>
      <param name="Append" value="false" />
      <param name="MaxFileSize" value="10MB"/>
      <param name="MaxBackupIndex" value="10"/>
      <layout class="org.apache.log4j.PatternLayout">
         <param name="ConversionPattern"
            value="%d{ISO8601} %p - %t - %c - %m%n"/>
      </layout>
   </appender>

I simply added the following line:

<param name="Append" value="false" />

It now truncates the base log file at startup, but it leaves the rolled files alone.

回答1:

If you set the append parameter to false, the base log file will be "started fresh" when the application restarts. Do you mean that you want any "rolled" log files to be deleted too?



回答2:

I've written some custom code to find my RollingFileAppender (which is unnecessarily difficult to get access to in log4j!) which I then cause to roll over. I've adapted my code below for a single use. I use code similar to this at application startup to force my logs to roll (if non-empty) so I always start in a fresh log but never delete any log but the oldest.

This code takes a given Logger and loops up the logger hierarchy until it finds a Logger that has Appenders attached. If it never does, then it gives up. If it does, it loops over all Appenders attached to that Logger and for each one that is a RollingFileAppender, it forces the log to roll.

Something like this should be a lot easier to do in log4j, but I haven't found a simpler way of doing it.

public void rollLogFile(Logger logger) {
  while (logger != null && !logger.getAllAppenders().hasMoreElements()) {
    logger = (Logger)logger.getParent();
  }

  if (logger == null) {
    return;
  }

  for (Enumeration e2 = logger.getAllAppenders(); e2.hasMoreElements();) {
    final Appender appender = (Appender)e2.nextElement();
    if (appender instanceof RollingFileAppender) {
      final RollingFileAppender rfa = (RollingFileAppender)appender;
      final File logFile = new File(rfa.getFile());
      if (logFile.length() > 0) {
        rfa.rollOver();
      }
    }
  }
}