FileDocCategorySizeDatePackage
CompositeRollingAppender.javaAPI DocApache log4j 1.2.1522665Sat Aug 25 00:09:36 BST 2007org.apache.log4j

CompositeRollingAppender

public class CompositeRollingAppender extends FileAppender

CompositeRollingAppender combines RollingFileAppender and DailyRollingFileAppender
It can function as either or do both at the same time (making size based rolling files like RollingFileAppender until a data/time boundary is crossed at which time it rolls all of those files as per the DailyRollingFileAppender) based on the setting for rollingStyle.

To use CompositeRollingAppender to roll log files as they reach a certain size (like RollingFileAppender), set rollingStyle=1 (@see config.size)
To use CompositeRollingAppender to roll log files at certain time intervals (daily for example), set rollingStyle=2 and a datePattern (@see config.time)
To have CompositeRollingAppender roll log files at a certain size AND rename those according to time intervals, set rollingStyle=3 (@see config.composite)

A of few additional optional features have been added:
-- Attach date pattern for current log file (@see staticLogFileName)
-- Backup number increments for newer files (@see countDirection)
-- Infinite number of backups by file size (@see maxSizeRollBackups)

A few notes and warnings: For large or infinite number of backups countDirection > 0 is highly recommended, with staticLogFileName = false if time based rolling is also used -- this will reduce the number of file renamings to few or none. Changing staticLogFileName or countDirection without clearing the directory could have nasty side effects. If Date/Time based rolling is enabled, CompositeRollingAppender will attempt to roll existing files in the directory without a date/time tag based on the last modified date of the base log files last modification.

A maximum number of backups based on date/time boundries would be nice but is not yet implemented.

author
Kevin Steppe
author
Heinz Richter
author
Eirik Lygre
author
Ceki Gülcü

Fields Summary
static final int
TOP_OF_TROUBLE
static final int
TOP_OF_MINUTE
static final int
TOP_OF_HOUR
static final int
HALF_DAY
static final int
TOP_OF_DAY
static final int
TOP_OF_WEEK
static final int
TOP_OF_MONTH
static final int
BY_SIZE
Style of rolling to use
static final int
BY_DATE
static final int
BY_COMPOSITE
static final String
S_BY_SIZE
static final String
S_BY_DATE
static final String
S_BY_COMPOSITE
private String
datePattern
The date pattern. By default, the pattern is set to "'.'yyyy-MM-dd" meaning daily rollover.
private String
scheduledFilename
The actual formatted filename that is currently being written to or will be the file transferred to on roll over (based on staticLogFileName).
private long
nextCheck
The timestamp when we shall next recompute the filename.
Date
now
Holds date of last roll over
SimpleDateFormat
sdf
RollingCalendar
rc
Helper class to determine next rollover time
int
checkPeriod
Current period for roll overs
protected long
maxFileSize
The default maximum file size is 10MB.
protected int
maxSizeRollBackups
There is zero backup files by default.
protected int
curSizeRollBackups
How many sized based backups have been made so far
protected int
maxTimeRollBackups
not yet implemented
protected int
curTimeRollBackups
protected int
countDirection
By default newer files have lower numbers. (countDirection < 0) ie. log.1 is most recent, log.5 is the 5th backup, etc... countDirection > 0 does the opposite ie. log.1 is the first backup made, log.5 is the 5th backup made, etc. For infinite backups use countDirection > 0 to reduce rollOver costs.
protected int
rollingStyle
Style of rolling to Use. BY_SIZE (1), BY_DATE(2), BY COMPOSITE(3)
protected boolean
rollDate
protected boolean
rollSize
protected boolean
staticLogFileName
By default file.log is always the current file. Optionally file.log.yyyy-mm-dd for current formated datePattern can by the currently logging file (or file.log.curSizeRollBackup or even file.log.yyyy-mm-dd.curSizeRollBackup) This will make time based roll overs with a large number of backups much faster -- it won't have to rename all the backups!
protected String
baseFileName
FileName provided in configuration. Used for rolling properly
Constructors Summary
public CompositeRollingAppender()
The default constructor does nothing.


          
	   
    
public CompositeRollingAppender(Layout layout, String filename, String datePattern)
Instantiate a CompositeRollingAppender and open the file designated by filename. The opened filename will become the ouput destination for this appender.

	    this(layout, filename, datePattern, true);
	
public CompositeRollingAppender(Layout layout, String filename, boolean append)
Instantiate a CompositeRollingAppender and open the file designated by filename. The opened filename will become the ouput destination for this appender.

If the append parameter is true, the file will be appended to. Otherwise, the file desginated by filename will be truncated before being opened.

	    super(layout, filename, append);
	
public CompositeRollingAppender(Layout layout, String filename, String datePattern, boolean append)
Instantiate a CompositeRollingAppender and open the file designated by filename. The opened filename will become the ouput destination for this appender.

	    super(layout, filename, append);
	    this.datePattern = datePattern;
		activateOptions();
	
public CompositeRollingAppender(Layout layout, String filename)
Instantiate a CompositeRollingAppender and open the file designated by filename. The opened filename will become the output destination for this appender.

The file will be appended to. DatePattern is default.

	    super(layout, filename);
	
Methods Summary
public voidactivateOptions()
Sets initial conditions including date/time roll over information, first check, scheduledFilename, and calls existingInit to initialize the current # of backups.


	    //REMOVE removed rollDate from boolean to enable Alex's change
		if(datePattern != null) {
			now.setTime(System.currentTimeMillis());
			sdf = new SimpleDateFormat(datePattern);
			int type = computeCheckPeriod();
			//printPeriodicity(type);
			rc.setType(type);
			//next line added as this removes the name check in rollOver
			nextCheck = rc.getNextCheckMillis(now);
		} else {
			if (rollDate)
			    LogLog.error("Either DatePattern or rollingStyle options are not set for ["+
			      name+"].");
		}

		existingInit();

		super.activateOptions();

		if (rollDate && fileName != null && scheduledFilename == null)
			scheduledFilename = fileName + sdf.format(now);
	
intcomputeCheckPeriod()

		RollingCalendar c = new RollingCalendar();
		// set sate to 1970-01-01 00:00:00 GMT
		Date epoch = new Date(0);
		if(datePattern != null) {
			for(int i = TOP_OF_MINUTE; i <= TOP_OF_MONTH; i++) {
				String r0 = sdf.format(epoch);
				c.setType(i);
				Date next = new Date(c.getNextCheckMillis(epoch));
				String r1 = sdf.format(next);
				//LogLog.debug("Type = "+i+", r0 = "+r0+", r1 = "+r1);
				if(r0 != null && r1 != null && !r0.equals(r1)) {
					return i;
				}
			}
		}
		return TOP_OF_TROUBLE; // Deliberately head for trouble...
	
protected static voiddeleteFile(java.lang.String fileName)
Delete's the specified file if it exists

		File file = new File(fileName);
		if (file.exists()) {
		   file.delete();
		}
	
protected voidexistingInit()
Initializes based on exisiting conditions at time of activateOptions. The following is done:

A) determine curSizeRollBackups
B) determine curTimeRollBackups (not implemented)
C) initiates a roll over if needed for crossing a date boundary since the last run.


		curSizeRollBackups = 0;
		curTimeRollBackups = 0;

		//part A starts here
		String filter;
		if (staticLogFileName || !rollDate) {
			filter = baseFileName + ".*";
		}
		else {
			filter = scheduledFilename + ".*";
		}

		File f = new File(baseFileName);
		f = f.getParentFile();
		if (f == null)
		   f = new File(".");

		LogLog.debug("Searching for existing files in: " + f);
		String[] files = f.list();

		if (files != null) {
			for (int i = 0; i < files.length; i++) {
				if (!files[i].startsWith(baseFileName))
				   continue;

				int index = files[i].lastIndexOf(".");

				if (staticLogFileName) {
				   int endLength = files[i].length() - index;
				   if (baseFileName.length() + endLength != files[i].length()) {
					   //file is probably scheduledFilename + .x so I don't care
					   continue;
				   }
				}

				try {
					int backup = Integer.parseInt(files[i].substring(index + 1, files[i].length()));
					LogLog.debug("From file: " + files[i] + " -> " + backup);
					if (backup > curSizeRollBackups)
					   curSizeRollBackups = backup;
				}
				catch (Exception e) {
					//this happens when file.log -> file.log.yyyy-mm-dd which is normal
					//when staticLogFileName == false
					LogLog.debug("Encountered a backup file not ending in .x " + files[i]);
				}
			}
		}
		LogLog.debug("curSizeRollBackups starts at: " + curSizeRollBackups);
		//part A ends here

		//part B not yet implemented

		//part C
		if (staticLogFileName && rollDate) {
			File old = new File(baseFileName);
			if (old.exists()) {
				Date last = new Date(old.lastModified());
				if (!(sdf.format(last).equals(sdf.format(now)))) {
					scheduledFilename = baseFileName + sdf.format(last);
					LogLog.debug("Initial roll over to: " + scheduledFilename);
					rollOverTime();
				}
			}
		}
		LogLog.debug("curSizeRollBackups after rollOver at: " + curSizeRollBackups);
		//part C ends here

	
public intgetCountDirection()

		return countDirection;
	
public java.lang.StringgetDatePattern()
Returns the value of the DatePattern option.

	    return datePattern;
	
public intgetMaxSizeRollBackups()
Returns the value of the maxSizeRollBackups option.

	    return maxSizeRollBackups;
	
public longgetMaximumFileSize()
Get the maximum size that the output file is allowed to reach before being rolled over to backup files.

since
1.1

		return maxFileSize;
	
public intgetRollingStyle()

        return rollingStyle;
	
public booleangetStaticLogFileName()

	    return staticLogFileName;
	
protected static voidrollFile(java.lang.String from, java.lang.String to)
Renames file from to file to. It also checks for existence of target file and deletes if it does.

		File target = new File(to);
		if (target.exists()) {
			LogLog.debug("deleting existing target file: " + target);
			target.delete();
		}

		File file = new File(from);
		file.renameTo(target);
		LogLog.debug(from +" -> "+ to);
	
protected voidrollOverSize()
Implements roll overs base on file size.

If the maximum number of size based backups is reached (curSizeRollBackups == maxSizeRollBackups If countDirection < 0, then files {File.1, ..., File.curSizeRollBackups -1} are renamed to {File.2, ..., File.curSizeRollBackups}. Moreover, File is renamed File.1 and closed.
A new file is created to receive further log output.

If maxSizeRollBackups is equal to zero, then the File is truncated with no backup files created.

If maxSizeRollBackups < 0, then File is renamed if needed and no files are deleted.

		File file;

		this.closeFile(); // keep windows happy.

		LogLog.debug("rolling over count=" + ((CountingQuietWriter) qw).getCount());
		LogLog.debug("maxSizeRollBackups = " + maxSizeRollBackups);
		LogLog.debug("curSizeRollBackups = " + curSizeRollBackups);
		LogLog.debug("countDirection = " + countDirection);

		// If maxBackups <= 0, then there is no file renaming to be done.
		if (maxSizeRollBackups != 0) {

			if (countDirection < 0) {
				// Delete the oldest file, to keep Windows happy.
				if (curSizeRollBackups == maxSizeRollBackups) {
				    deleteFile(fileName + '." + maxSizeRollBackups);
					curSizeRollBackups--;
				}

				// Map {(maxBackupIndex - 1), ..., 2, 1} to {maxBackupIndex, ..., 3, 2}
				for (int i = curSizeRollBackups; i >= 1; i--) {
					rollFile((fileName + "." + i), (fileName + '." + (i + 1)));
				}

				curSizeRollBackups++;
				// Rename fileName to fileName.1
				rollFile(fileName, fileName + ".1");

			} //REMOVE This code branching for Alexander Cerna's request
			else if (countDirection == 0) {
				//rollFile based on date pattern
				curSizeRollBackups++;
				now.setTime(System.currentTimeMillis());
				scheduledFilename = fileName + sdf.format(now);
				rollFile(fileName, scheduledFilename);
			}
			else { //countDirection > 0
				if (curSizeRollBackups >= maxSizeRollBackups && maxSizeRollBackups > 0) {
					//delete the first and keep counting up.
					int oldestFileIndex = curSizeRollBackups - maxSizeRollBackups + 1;
					deleteFile(fileName + '." + oldestFileIndex);
				}

				if (staticLogFileName) {
					curSizeRollBackups++;
					rollFile(fileName, fileName + '." + curSizeRollBackups);
				}
			}
		}

		try {
			// This will also close the file. This is OK since multiple
			// close operations are safe.
			this.setFile(baseFileName, false);
		}
		catch(IOException e) {
			LogLog.error("setFile("+fileName+", false) call failed.", e);
		}
	
protected voidrollOverTime()
Rollover the file(s) to date/time tagged file(s). Opens the new file (through setFile) and resets curSizeRollBackups.


	    curTimeRollBackups++;

		//delete the old stuff here

		if (staticLogFileName) {
			/* Compute filename, but only if datePattern is specified */
			if (datePattern == null) {
				errorHandler.error("Missing DatePattern option in rollOver().");
				return;
			}

			//is the new file name equivalent to the 'current' one
			//something has gone wrong if we hit this -- we should only
			//roll over if the new file will be different from the old
			String dateFormat = sdf.format(now);
			if (scheduledFilename.equals(fileName + dateFormat)) {
				errorHandler.error("Compare " + scheduledFilename + " : " + fileName + dateFormat);
				return;
			}

			// close current file, and rename it to datedFilename
			this.closeFile();

			//we may have to roll over a large number of backups here
	        String from, to;
			for (int i = 1; i <= curSizeRollBackups; i++) {
				from = fileName + '." + i;
				to = scheduledFilename + '." + i;
				rollFile(from, to);
	        }

			rollFile(fileName, scheduledFilename);
		}

		try {
			// This will also close the file. This is OK since multiple
			// close operations are safe.
			curSizeRollBackups = 0; //We're cleared out the old date and are ready for the new

			//new scheduled name
			scheduledFilename = fileName + sdf.format(now);
			this.setFile(baseFileName, false);
		}
		catch(IOException e) {
			errorHandler.error("setFile("+fileName+", false) call failed.");
		}

	
public voidsetCountDirection(int direction)

		countDirection = direction;
	
public voidsetDatePattern(java.lang.String pattern)
The DatePattern takes a string in the same format as expected by {@link SimpleDateFormat}. This options determines the rollover schedule.

	    datePattern = pattern;
	
public voidsetFile(java.lang.String file)

		baseFileName = file.trim();
		fileName = file.trim();
	
public synchronized voidsetFile(java.lang.String fileName, boolean append)
Creates and opens the file for logging. If staticLogFileName is false then the fully qualified name is determined and used.

		if (!staticLogFileName) {
		    scheduledFilename = fileName = fileName.trim() + sdf.format(now);
			if (countDirection > 0) {
				scheduledFilename = fileName = fileName + '." + (++curSizeRollBackups);
			}
		}

		super.setFile(fileName, append);
		if(append) {
		  File f = new File(fileName);
		  ((CountingQuietWriter) qw).setCount(f.length());
		}
	
public voidsetMaxFileSize(long maxFileSize)
Set the maximum size that the output file is allowed to reach before being rolled over to backup files.

This method is equivalent to {@link #setMaxFileSize} except that it is required for differentiating the setter taking a long argument from the setter taking a String argument by the JavaBeans {@link java.beans.Introspector Introspector}.

see
#setMaxFileSize(String)

	   this.maxFileSize = maxFileSize;
	
public voidsetMaxFileSize(java.lang.String value)
Set the maximum size that the output file is allowed to reach before being rolled over to backup files.

In configuration files, the MaxFileSize option takes an long integer in the range 0 - 2^63. You can specify the value with the suffixes "KB", "MB" or "GB" so that the integer is interpreted being expressed respectively in kilobytes, megabytes or gigabytes. For example, the value "10KB" will be interpreted as 10240.

	    maxFileSize = OptionConverter.toFileSize(value, maxFileSize + 1);
	
public voidsetMaxSizeRollBackups(int maxBackups)

Set the maximum number of backup files to keep around based on file size.

The MaxSizeRollBackups option determines how many backup files are kept before the oldest is erased. This option takes an integer value. If set to zero, then there will be no backup files and the log file will be truncated when it reaches MaxFileSize. If a negative number is supplied then no deletions will be made. Note that this could result in very slow performance as a large number of files are rolled over unless {@link #setCountDirection} up is used.

The maximum applys to -each- time based group of files and -not- the total. Using a daily roll the maximum total files would be (#days run) * (maxSizeRollBackups)

	    maxSizeRollBackups = maxBackups;
	
public voidsetMaximumFileSize(long maxFileSize)
Set the maximum size that the output file is allowed to reach before being rolled over to backup files.

This method is equivalent to {@link #setMaxFileSize} except that it is required for differentiating the setter taking a long argument from the setter taking a String argument by the JavaBeans {@link java.beans.Introspector Introspector}.

see
#setMaxFileSize(String)

		this.maxFileSize = maxFileSize;
	
protected voidsetQWForFiles(java.io.Writer writer)

	    qw = new CountingQuietWriter(writer, errorHandler);
	
public voidsetRollingStyle(int style)

	    rollingStyle = style;
		switch (rollingStyle) {
			case BY_SIZE:
				 rollDate = false;
				 rollSize = true;
				 break;
			case BY_DATE:
				 rollDate = true;
				 rollSize = false;
				 break;
			case BY_COMPOSITE:
				 rollDate = true;
				 rollSize = true;
				 break;
			default:
				errorHandler.error("Invalid rolling Style, use 1 (by size only), 2 (by date only) or 3 (both)");
		}
	
public voidsetStaticLogFileName(boolean s)

		staticLogFileName = s;
	
public voidsetStaticLogFileName(java.lang.String value)

		setStaticLogFileName(OptionConverter.toBoolean(value, true));
	
protected voidsubAppend(org.apache.log4j.spi.LoggingEvent event)
Handles append time behavior for CompositeRollingAppender. This checks if a roll over either by date (checked first) or time (checked second) is need and then appends to the file last.


		if (rollDate) {
			long n = System.currentTimeMillis();
			if (n >= nextCheck) {
				now.setTime(n);
				nextCheck = rc.getNextCheckMillis(now);

				rollOverTime();
			}
		}

		if (rollSize) {
			if ((fileName != null) && ((CountingQuietWriter) qw).getCount() >= maxFileSize) {
			    rollOverSize();
			}
		}

		super.subAppend(event);