Table of Contents

Class RollingFileAppender

Namespace
log4net.Appender
Assembly
log4net.dll

Appender that rolls log files based on size or date or both.

public class RollingFileAppender : FileAppender, IBulkAppender, IAppender, IOptionHandler
Inheritance
RollingFileAppender
Implements
Inherited Members

Remarks

RollingFileAppender can roll log files based on size or date or both depending on the setting of the RollingStyle property. When set to Size the log file will be rolled once its size exceeds the MaximumFileSize. When set to Date the log file will be rolled once the date boundary specified in the DatePattern property is crossed. When set to Composite the log file will be rolled once the date boundary specified in the DatePattern property is crossed, but within a date boundary the file will also be rolled once its size exceeds the MaximumFileSize. When set to Once the log file will be rolled when the appender is configured. This effectively means that the log file can be rolled once per program execution.

A of few additional optional features have been added:

note

For large or infinite numbers of backup files a CountDirection greater than zero is highly recommended, otherwise all the backup files need to be renamed each time a new backup is created.

When Date/Time based rolling is used setting StaticLogFileName to true will reduce the number of file renamings to few or none.

caution

Changing StaticLogFileName or CountDirection without clearing the log file directory of backup files will cause unexpected and unwanted side effects.

If Date/Time based rolling is enabled this appender will attempt to roll existing files in the directory without a Date/Time tag based on the last write date of the base log file. The appender only rolls the log file when a message is logged. If Date/Time based rolling is enabled then the appender will not roll the log file at the Date/Time boundary but at the point when the next message is logged after the boundary has been crossed.

The RollingFileAppender extends the FileAppender and has the same behavior when opening the log file. The appender will first try to open the file for writing when ActivateOptions() is called. This will typically be during configuration. If the file cannot be opened for writing the appender will attempt to open the file again each time a message is logged to the appender. If the file cannot be opened for writing when a message is logged then the message will be discarded by this appender.

When rolling a backup file necessitates deleting an older backup file the file to be deleted is moved to a temporary name before being deleted.

caution

A maximum number of backup files when rolling on date/time boundaries is not supported.

Constructors

RollingFileAppender()

Initializes a new instance of the RollingFileAppender class.

public RollingFileAppender()

Remarks

Default constructor.

Properties

CountDirection

Gets or sets the rolling file count direction.

public int CountDirection { get; set; }

Property Value

int

The rolling file count direction.

Remarks

Indicates if the current file is the lowest numbered file or the highest numbered file.

By default newer files have lower numbers (CountDirection < 0), i.e. log.1 is most recent, log.5 is the 5th backup, etc...

CountDirection >= 0 does the opposite i.e. 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.

The default file count direction is -1.

DatePattern

Gets or sets the date pattern to be used for generating file names when rolling over on date.

public string DatePattern { get; set; }

Property Value

string

The date pattern to be used for generating file names when rolling over on date.

Remarks

Takes a string in the same format as expected by SimpleDateFormatter.

This property determines the rollover schedule when rolling over on date.

DateTimeStrategy

Gets or sets the strategy for determining the current date and time. The default implementation is to use LocalDateTime which internally calls through to DateTime.Now. DateTime.UtcNow may be used on frameworks newer than .NET 1.0 by specifying RollingFileAppender.UniversalDateTime.

public RollingFileAppender.IDateTime DateTimeStrategy { get; set; }

Property Value

RollingFileAppender.IDateTime

An implementation of the RollingFileAppender.IDateTime interface which returns the current date and time.

Remarks

Gets or sets the RollingFileAppender.IDateTime used to return the current date and time.

There are two built strategies for determining the current date and time, RollingFileAppender.LocalDateTime and RollingFileAppender.UniversalDateTime.

The default strategy is RollingFileAppender.LocalDateTime.

MaxFileSize

Gets or sets the maximum size that the output file is allowed to reach before being rolled over to backup files.

public long MaxFileSize { get; set; }

Property Value

long

The maximum size in bytes that the output file is allowed to reach before being rolled over to backup files.

Remarks

This property is equivalent to MaximumFileSize except that it is required for differentiating the setter taking a long argument from the setter taking a string argument.

The default maximum file size is 10MB (10*1024*1024).

MaxSizeRollBackups

Gets or sets the maximum number of backup files that are kept before the oldest is erased.

public int MaxSizeRollBackups { get; set; }

Property Value

int

The maximum number of backup files that are kept before the oldest is erased.

Remarks

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 CountDirection is used.

The maximum applies to each time based group of files and not the total.

MaximumFileSize

Gets or sets the maximum size that the output file is allowed to reach before being rolled over to backup files.

public string MaximumFileSize { get; set; }

Property Value

string

The maximum size that the output file is allowed to reach before being rolled over to backup files.

Remarks

This property allows you to specify the maximum size with the suffixes "KB", "MB" or "GB" so that the size is interpreted being expressed respectively in kilobytes, megabytes or gigabytes.

For example, the value "10KB" will be interpreted as 10240 bytes.

The default maximum file size is 10MB.

If you have the option to set the maximum file size programmatically consider using the MaxFileSize property instead as this allows you to set the size in bytes as a long.

PreserveLogFileNameExtension

Gets or sets a value indicating whether to preserve the file name extension when rolling.

public bool PreserveLogFileNameExtension { get; set; }

Property Value

bool

true if the file name extension should be preserved.

Remarks

By default file.log is rolled to file.log.yyyy-MM-dd or file.log.curSizeRollBackup. However, under Windows the new file name will loose any program associations as the extension is changed. Optionally file.log can be renamed to file.yyyy-MM-dd.log or file.curSizeRollBackup.log to maintain any program associations.

RollingStyle

Gets or sets the rolling style.

public RollingFileAppender.RollingMode RollingStyle { get; set; }

Property Value

RollingFileAppender.RollingMode

The rolling style.

Remarks

The default rolling style is Composite.

When set to Once this appender's AppendToFile property is set to false, otherwise the appender would append to a single file rather than rolling the file each time it is opened.

StaticLogFileName

Gets or sets a value indicating whether to always log to the same file.

public bool StaticLogFileName { get; set; }

Property Value

bool

true if always should be logged to the same file, otherwise false.

Remarks

By default file.log is always the current file. Optionally file.log.yyyy-mm-dd for current formatted datePattern can by the currently logging file (or file.log.curSizeRollBackup or even file.log.yyyy-mm-dd.curSizeRollBackup).

This will make time based rollovers with a large number of backups much faster as the appender it won't have to rename all the backups!

Methods

ActivateOptions()

Initialize the appender based on the options set

public override void ActivateOptions()

Remarks

This is part of the IOptionHandler delayed object activation scheme. The ActivateOptions() method must be called on this object after the configuration properties have been set. Until ActivateOptions() is called this object is in an undefined state and must not be used.

If any of the configuration properties are modified then ActivateOptions() must be called again.

Sets initial conditions including date/time roll over information, first check, scheduledFilename, and calls ExistingInit() to initialize the current number of backups.

AdjustFileBeforeAppend()

Performs any required rolling before outputting the next event

protected virtual void AdjustFileBeforeAppend()

Remarks

Handles append time behavior for RollingFileAppender. This checks if a roll over either by date (checked first) or time (checked second) is need and then appends to the file last.

Append(LoggingEvent)

Write out a logging event.

protected override void Append(LoggingEvent loggingEvent)

Parameters

loggingEvent LoggingEvent

the event to write to file.

Remarks

Handles append time behavior for RollingFileAppender. This checks if a roll over either by date (checked first) or time (checked second) is need and then appends to the file last.

Append(LoggingEvent[])

Write out an array of logging events.

protected override void Append(LoggingEvent[] loggingEvents)

Parameters

loggingEvents LoggingEvent[]

the events to write to file.

Remarks

Handles append time behavior for RollingFileAppender. This checks if a roll over either by date (checked first) or time (checked second) is need and then appends to the file last.

DeleteFile(string)

Deletes the specified file if it exists.

protected void DeleteFile(string fileName)

Parameters

fileName string

The file to delete.

Remarks

Delete a file if is exists. The file is first moved to a new filename then deleted. This allows the file to be removed even when it cannot be deleted, but it still can be moved.

ExistingInit()

Initializes based on existing conditions at time of ActivateOptions().

protected void ExistingInit()

Remarks

Initializes based on existing conditions at time of ActivateOptions(). The following is done

  • determine curSizeRollBackups (only within the current roll point)
  • initiates a roll over if needed for crossing a date boundary since the last run.

FileExists(string)

Test if a file exists at a specified path

protected bool FileExists(string path)

Parameters

path string

the path to the file

Returns

bool

true if the file exists

Remarks

Test if a file exists at a specified path

GetNextOutputFileName(string)

Get the current output file name

protected string GetNextOutputFileName(string fileName)

Parameters

fileName string

the base file name

Returns

string

the output file name

Remarks

The output file name is based on the base fileName specified. If StaticLogFileName is set then the output file name is the same as the base file passed in. Otherwise the output file depends on the date pattern, on the count direction or both.

NextCheckDate(DateTime, RollPoint)

Get the start time of the next window for the current rollpoint

protected DateTime NextCheckDate(DateTime currentDateTime, RollingFileAppender.RollPoint rollPoint)

Parameters

currentDateTime DateTime

the current date

rollPoint RollingFileAppender.RollPoint

the type of roll point we are working with

Returns

DateTime

the start time for the next roll point an interval after the currentDateTime date

Remarks

Returns the date of the next roll point after the currentDateTime date passed to the method.

The basic strategy is to subtract the time parts that are less significant than the rollpoint from the current time. This should roll the time back to the start of the time window for the current rollpoint. Then we add 1 window worth of time and get the start time of the next window for the rollpoint.

OpenFile(string, bool)

Creates and opens the file for logging. If StaticLogFileName is false then the fully qualified name is determined and used.

protected override void OpenFile(string fileName, bool append)

Parameters

fileName string

the name of the file to open

append bool

true to append to existing file

Remarks

This method will ensure that the directory structure for the fileName specified exists.

RollFile(string, string)

Renames file fromFile to file toFile.

protected void RollFile(string fromFile, string toFile)

Parameters

fromFile string

Name of existing file to roll.

toFile string

New name for file.

Remarks

Renames file fromFile to file toFile. It also checks for existence of target file and deletes if it does.

RollOverRenameFiles(string)

Implements file roll.

protected void RollOverRenameFiles(string baseFileName)

Parameters

baseFileName string

the base name to rename

Remarks

If the maximum number of size based backups is reached (curSizeRollBackups == maxSizeRollBackups) then the oldest file is deleted -- its index determined by the sign of countDirection. If countDirection < 0, then files {File.1, ..., File.curSizeRollBackups -1} are renamed to {File.2, ..., File.curSizeRollBackups}.

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.

This is called by RollOverSize() to rename the files.

RollOverSize()

Implements file roll base on file size.

protected void RollOverSize()

Remarks

If the maximum number of size based backups is reached (curSizeRollBackups == maxSizeRollBackups) then the oldest file is deleted -- its index determined by the sign of countDirection. 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.

RollOverTime(bool)

Rollover the file(s) to date/time tagged file(s).

protected void RollOverTime(bool fileIsOpen)

Parameters

fileIsOpen bool

set to true if the file to be rolled is currently open

Remarks

Rollover the file(s) to date/time tagged file(s). Resets curSizeRollBackups. If fileIsOpen is set then the new file is opened (through SafeOpenFile).

SetQWForFiles(TextWriter)

Sets the quiet writer being used.

protected override void SetQWForFiles(TextWriter writer)

Parameters

writer TextWriter

the writer to set

Remarks

This method can be overridden by sub classes.