Jim,

Ooops! I got a DateRollingAppender from you too? Eirik Lygre has also sent 
me one. Roberto Leong has too. Their contributions are attached.
Jim, can you please repost your contribution on this list? I seem to have 
lost it. Sorry, I haven't been handling this item particularly well.

What I would like to see is the following:

0) Keep in mind that log4j is not in the quickie business. Much of the 
success of the package can be attributed to solving problems well, not just 
solving them.

1) The new appender should have flexible way of expressing the rollover 
frequency, perhaps in the same format as in the Unix crontabs file which I 
belive is also a Posix standard. I am not aware of any library that 
supports this. JDring (http://webtools.dyade.fr/jdring/) seems to have most 
of the functionality needed except parsing the crontab format. Anyone know 
anything better?

As a side note, the omission of a crontab/at functionality in Java core 
libraries seems like a major oversight. Try buying stock a day later then 
what the customer ordered. See how many customers stay with your brokerage 
house.  :-)

2) The new appender should not add any significant overhead to the append 
method. If appending to a file takes 100 microseconds in a particular 
environment it should still take 100 microseconds with the new appender.

There are several possible designs. The first one is to check for the 
rollover condition at each append. This is what Eirik Lygre has done. The 
second one is to schedule a thread that will initiate the rollover after 
the appropriate delay. This is what Roberto Leong has proposed.

The second approach seems more sound to me. One could generalize it by 
using a single timer  thread (as in JDring) to manage multiple time based 
RollingAppenders. Your opinion/comments are welcome. Ceki


ps: I am forwarding this to the Avalon list since they are writing a 
general purpose framework.
ps: I wonder how Tomcat addresses the issue.


At 21:45 18.01.2001 -0500, you wrote:
>Yes, but you need to use a different Appender than FileRolloverAppender.
>I've already written one, but haven't heard back from Ceki about adding it
>to the "package" yet...
>
>-Jim Moore
>
>-----Original Message-----
>From: Andrewt Tierney [mailto:[EMAIL PROTECTED]]
>Sent: Thursday, January 18, 2001 8:02 PM
>To: '[EMAIL PROTECTED]'
>Subject: Rollover for each day ? Is this possible ??
>
>
>
>I see you can set the maxsize and have it automatically rollover the log
>file.
>
>Is it possible to force a new log file each day ????
>
>Thanks
>Andrew
>
>---------------------------------------------------------------------
>To unsubscribe, e-mail: [EMAIL PROTECTED]
>For additional commands, e-mail: [EMAIL PROTECTED]

---
Freedom as in the capacity to exercise choice.
package org.log4j.varia;

import org.log4j.FileAppender;
import org.log4j.helpers.TracerPrintWriter;
import org.log4j.helpers.LogLog;

import java.text.SimpleDateFormat;
import java.io.IOException;
import java.io.FileWriter;
import java.util.Calendar;



// Roberto Leong <[EMAIL PROTECTED]>

/**
   DailyFileAppender extends FileAppender to backup the log files when 
   the day changes. Basically a new log file will automatically
   be created everyday.
   
*/
        
public class DailyFileAppender extends FileAppender {
  
  // formatter for date
  SimpleDateFormat formatter = null;
  
  // pattern for date 
  String dateFormat = "yyyy-MM-dd";      
  
    {      
      formatter = new SimpleDateFormat(dateFormat);
    }
  
  // 
  
  // filename without the day part
  String unformattedFileName = null;
   
  /**
     Activates the thread that checks the day
     {@link #setOption}.  */
  public void activateOptions() {
    super.activateOptions();
    new Thread(new DayChecker(this)).start();
  }
   

  /**
     Overrides FileAppender.setFile(String fileName, boolean append) to append 
     today´s day to the filename
    
    
    @param fileName The path to the log file.
    @param boolean If true will append to fileName. Otherwise will
    truncate fileName.  */
    
  public 
  synchronized 
  void setFile(String fileName, boolean append) throws IOException {
                
    unformattedFileName = new String(fileName);
    boolean hasDot = false;

    //finds the first and hopefully only '.' and appends today's day before it.
    // If no '.' is found just add it to end of the filename
    for(int i=0; i<fileName.length(); i++) {
      if(fileName.charAt(i)=='.') {
        String str = fileName.substring(0, i);
        fileName = str + formatter.format(Calendar.getInstance().getTime()) + 
          fileName.substring(i);
        hasDot = true;
        break;
      }
    }
    
    if(!hasDot)
      fileName = fileName + formatter.format(Calendar.getInstance().getTime());
    
    reset();
    this.setQWForFiles(new FileWriter(fileName, append));
    this.tp = new TracerPrintWriter(qw);
    this.fileName = fileName;
    this.qwIsOurs = true;
  }

                  
  class DayChecker implements Runnable {
    DailyFileAppender _dfa;
    String today = formatter.format(Calendar.getInstance().getTime());
    boolean refreshed = false;
    //      Calendar _tomorrow;
    
    public DayChecker(DailyFileAppender dfa) {
      _dfa = dfa;
    }
    
    public void run() {
      for(;;) {        
        int dif = 24 - Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
        String dayChange = formatter.format(Calendar.getInstance().getTime());
        
        // day change          
        if(!today.equals(dayChange)) {
          today = dayChange;          
          try {              
            // refresh filename            
            _dfa.setFile(unformattedFileName, fileAppend);            
          }
          catch(IOException e) {
            LogLog.error("Unexpected exception.", e);                                  
 
          }
        }
        
        // almost day change sleep for a shorter period of time
        else if(dif == 1) {
          if(Calendar.getInstance().get(Calendar.MINUTE) >= 59) {
            sleep(1000 * 5);
          }
          else  
            sleep(1000 * 60);            
        }          
        else {
          // sleep for one hour
          sleep(60*60*1000);
        }          
      }        
    }
    
    private void sleep(long l) {
      try {
        Thread.currentThread().sleep(l);                
      }
      catch(InterruptedException e) {
        LogLog.error("Unexpected exception.", e); 
      }      
    }
  }  
} 
/*
 * Copyright (C) The Apache Software Foundation. All rights reserved.
 *
 * This software is published under the terms of the Apache Software
 * License version 1.1, a copy of which has been included with this
 * distribution in the LICENSE.APL file.  */



package org.apache.log4j;

import java.io.IOException;
import java.io.Writer;
import java.io.FileWriter;
import java.io.File;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.apache.log4j.helpers.OptionConverter;
import org.apache.log4j.helpers.QuietWriter;
import org.apache.log4j.helpers.CountingQuietWriter;
import org.apache.log4j.spi.LoggingEvent;
import org.apache.log4j.spi.ErrorCode;

/**
   DailyFileAppender extends FileAppender to use filenames formatted with
   date/time information. The filename is recomputed every day at midnight.
   Note that the filename doesn't have to change every day, making it possible
   to have logfiles which are per-week or per-month.

   The appender computes the proper filename using the formats specified in
   <a href="http://java.sun.com/j2se/1.3/docs/api/java/text/SimpleDateFormat.html">
   java.text.SimpleDateFormat</a>. The format requires that most static text is
   enclosed in single quotes, which are removed. The examples below show how
   quotes are used to embed static information in the format.

   Sample filenames:

<code>
     Filename pattern                     Filename
     "'/logs/trace-'yyyy-MM-dd'.log'"     /logs/trace-2000-12-31.log
     "'/logs/trace-'yyyy-ww'.log'"        /logs/trace-2000-52.log
</code>

   @author <a HREF="mailto:[EMAIL PROTECTED]">Eirik Lygre</a>
*/
public class DailyFileAppender extends FileAppender {

  /**
     A string constant used in naming the option for setting the
     filename pattern. Current value of this string constant is
     <strong>FileNamePattern</strong>.
   */
  static final public String FILE_NAME_PATTERN_OPTION = "FilePattern";
  
  /**
     The filename pattern
  */
  private String fileNamePattern = null;

  /**
     The actual formatted filename that is currently being written to
  */
  private String currentFileName = null;

  /**
     The timestamp when we shall next recompute the filename
  */
  private long nextFilenameComputingMillis = System.currentTimeMillis () - 1;

  /**
     The default constructor does no longer set a default layout nor a
     default output target.  */
  public
  DailyFileAppender() {
  }

  /**
    Instantiate a RollingFileAppender and open the file designated by
    <code>filename</code>. The opened filename will become the ouput
    destination for this appender.

    <p>If the <code>append</code> parameter is true, the file will be
    appended to. Otherwise, the file desginated by
    <code>filename</code> will be truncated before being opened.
  */
  public DailyFileAppender (Layout layout,String filename,boolean append) throws 
IOException {
    super(layout, filename, append);
  }

  /**
     Instantiate a FileAppender and open the file designated by
    <code>filename</code>. The opened filename will become the output
    destination for this appender.

    <p>The file will be appended to.  */
  public DailyFileAppender (Layout layout,String filename) throws IOException {
    super(layout, filename);
  }
  
  /**
     Set the current output file.

     The function will compute a new filename, and open a new file only
     when the name has changed.

     The function is automatically called once a day, to allow for
     daily files -- the purpose of this class.
  */

  public
  synchronized
  void setFile(String fileName, boolean append) throws IOException {

    /* Compute filename, but only if fileNamePattern is specified */
    if (fileNamePattern == null) {
      errorHandler.error("Missing file pattern (" + FILE_NAME_PATTERN_OPTION + ") in 
setFile().");
      return;
    }

    Date now = new Date();

    fileName = new SimpleDateFormat(fileNamePattern).format (now);
    if (fileName.equals(currentFileName))
      return;

    /* Set up next filename checkpoint */
    DailyFileAppenderCalendar c = new DailyFileAppenderCalendar();
    c.rollToNextDay ();
    nextFilenameComputingMillis = c.getTimeInMillis ();

    currentFileName = fileName;

    super.setFile(fileName, append);
  }

  /**
     This method differentiates RollingFileAppender from its super
     class.  

  */
  protected
  void subAppend(LoggingEvent event) {
     
     if (System.currentTimeMillis () >= nextFilenameComputingMillis) {
      try {
        setFile (super.fileName, super.fileAppend);
      }
      catch(IOException e) {
        System.err.println("setFile(null, false) call failed.");
        e.printStackTrace();
      }
    }

    super.subAppend(event);
  } 

  /**
     Retuns the option names for this component, namely {@link
     #FILE_NAME_PATTERN_OPTION} in
     addition to the options of {@link FileAppender#getOptionStrings
     FileAppender}.
  */
  public
  String[] getOptionStrings() {

    return OptionConverter.concatanateArrays(super.getOptionStrings(),
                 new String[] {FILE_NAME_PATTERN_OPTION});
  }

  /**
     Set the options for the appender
  */
  public
  void setOption(String key, String value) {
    super.setOption(key, value);    
    if(key.equalsIgnoreCase(FILE_NAME_PATTERN_OPTION)) {
      fileNamePattern = value;
    }
  }
  
  /**
     If the a value for {@link #FILE_OPTION} is non-null, then {@link
     #setFile} is called with the values of {@link #FILE_OPTION} and
     {@link #APPEND_OPTION}.

     @since 0.8.1 */
  public
  void activateOptions() {
    try {
           setFile(null, super.fileAppend);
    }
    catch(java.io.IOException e) {
           errorHandler.error("setFile(null,"+fileAppend+") call failed.",
                           e, ErrorCode.FILE_OPEN_FAILURE);
    }
  }
}

/**
   DailyFileAppenderCalendar is a helper class to DailyFileAppender. Using
   this class, it is easy to compute and access the next Millis()
 
   It subclasses the standard
   <a href="http://java.sun.com/j2se/1.3/docs/api/java/text/GregorianCalendar.html">
   java.util.GregorianCalendar</a>-object, to allow access to the protected
   function getTimeInMillis(), which it then exports.

   @author <a HREF="mailto:[EMAIL PROTECTED]">Eirik Lygre</a>
*/
class DailyFileAppenderCalendar extends java.util.GregorianCalendar
{
  /**
     Returns the current time in Millis
  */
  public long getTimeInMillis() {
    return super.getTimeInMillis();
  }

  /**
     Roll the date to the next hour, with minute, second and millisecond
     set to zero.
  */
  public void rollToNextDay () {
    this.add(java.util.Calendar.DATE, 0);
    this.add(java.util.Calendar.HOUR, 0);
    this.set(java.util.Calendar.MINUTE, 0);
    this.set(java.util.Calendar.SECOND, 0);
    this.set(java.util.Calendar.MILLISECOND, 0);
  }
}
---------------------------------------------------------------------
To unsubscribe, e-mail: [EMAIL PROTECTED]
For additional commands, email: [EMAIL PROTECTED]

Reply via email to