[ACCEPTED]-How do I make log4j clear a log at startup?-log4j

Accepted answer
Score: 47

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

Score: 5

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

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

Something like this should be 2 a lot easier to do in log4j, but I haven't 1 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();
      }
    }
  }
}

More Related questions