📄 rollingfileappender.cs
字号:
/// </para>
/// <para>
/// When set to <see cref="RollingMode.Once"/> this appender's
/// <see cref="FileAppender.AppendToFile"/> property is set to <c>false</c>, otherwise
/// the appender would append to a single file rather than rolling
/// the file each time it is opened.
/// </para>
/// </remarks>
public RollingMode RollingStyle
{
get { return m_rollingStyle; }
set
{
m_rollingStyle = value;
switch (m_rollingStyle)
{
case RollingMode.Once:
m_rollDate = false;
m_rollSize = false;
this.AppendToFile = false;
break;
case RollingMode.Size:
m_rollDate = false;
m_rollSize = true;
break;
case RollingMode.Date:
m_rollDate = true;
m_rollSize = false;
break;
case RollingMode.Composite:
m_rollDate = true;
m_rollSize = true;
break;
}
}
}
/// <summary>
/// Gets or sets a value indicating whether to always log to
/// the same file.
/// </summary>
/// <value>
/// <c>true</c> if always should be logged to the same file, otherwise <c>false</c>.
/// </value>
/// <remarks>
/// <para>
/// 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).
/// </para>
/// <para>
/// 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!
/// </para>
/// </remarks>
public bool StaticLogFileName
{
get { return m_staticLogFileName; }
set { m_staticLogFileName = value; }
}
#endregion Public Instance Properties
#region Override implementation of FileAppender
/// <summary>
/// Sets the quiet writer being used.
/// </summary>
/// <remarks>
/// This method can be overridden by sub classes.
/// </remarks>
/// <param name="writer">the writer to set</param>
override protected void SetQWForFiles(TextWriter writer)
{
QuietWriter = new CountingQuietTextWriter(writer, ErrorHandler);
}
/// <summary>
/// Write out a logging event.
/// </summary>
/// <param name="loggingEvent">the event to write to file.</param>
/// <remarks>
/// <para>
/// 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.
/// </para>
/// </remarks>
override protected void Append(LoggingEvent loggingEvent)
{
AdjustFileBeforeAppend();
base.Append(loggingEvent);
}
/// <summary>
/// Write out an array of logging events.
/// </summary>
/// <param name="loggingEvents">the events to write to file.</param>
/// <remarks>
/// <para>
/// 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.
/// </para>
/// </remarks>
override protected void Append(LoggingEvent[] loggingEvents)
{
AdjustFileBeforeAppend();
base.Append(loggingEvents);
}
/// <summary>
/// Performs any required rolling before outputting the next event
/// </summary>
/// <remarks>
/// <para>
/// 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.
/// </para>
/// </remarks>
virtual protected void AdjustFileBeforeAppend()
{
if (m_rollDate)
{
DateTime n = m_dateTime.Now;
if (n >= m_nextCheck)
{
m_now = n;
m_nextCheck = NextCheckDate(m_now, m_rollPoint);
RollOverTime(true);
}
}
if (m_rollSize)
{
if ((File != null) && ((CountingQuietTextWriter)QuietWriter).Count >= m_maxFileSize)
{
RollOverSize();
}
}
}
/// <summary>
/// Creates and opens the file for logging. If <see cref="StaticLogFileName"/>
/// is false then the fully qualified name is determined and used.
/// </summary>
/// <param name="fileName">the name of the file to open</param>
/// <param name="append">true to append to existing file</param>
/// <remarks>
/// <para>This method will ensure that the directory structure
/// for the <paramref name="fileName"/> specified exists.</para>
/// </remarks>
override protected void OpenFile(string fileName, bool append)
{
lock(this)
{
fileName = GetNextOutputFileName(fileName);
// Calculate the current size of the file
long currentCount = 0;
if (append)
{
using(SecurityContext.Impersonate(this))
{
if (System.IO.File.Exists(fileName))
{
currentCount = (new FileInfo(fileName)).Length;
}
}
}
else
{
if (LogLog.IsErrorEnabled)
{
// Internal check that the file is not being overwritten
// If not Appending to an existing file we should have rolled the file out of the
// way. Therefore we should not be over-writing an existing file.
// The only exception is if we are not allowed to roll the existing file away.
if (m_maxSizeRollBackups != 0 && FileExists(fileName))
{
LogLog.Error("RollingFileAppender: INTERNAL ERROR. Append is False but OutputFile ["+fileName+"] already exists.");
}
}
}
if (!m_staticLogFileName)
{
m_scheduledFilename = fileName;
}
// Open the file (call the base class to do it)
base.OpenFile(fileName, append);
// Set the file size onto the counting writer
((CountingQuietTextWriter)QuietWriter).Count = currentCount;
}
}
/// <summary>
/// Get the current output file name
/// </summary>
/// <param name="fileName">the base file name</param>
/// <returns>the output file name</returns>
/// <remarks>
/// The output file name is based on the base fileName specified.
/// If <see cref="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.
/// </remarks>
protected string GetNextOutputFileName(string fileName)
{
if (!m_staticLogFileName)
{
fileName = fileName.Trim();
if (m_rollDate)
{
fileName = fileName + m_now.ToString(m_datePattern, System.Globalization.DateTimeFormatInfo.InvariantInfo);
}
if (m_countDirection >= 0)
{
fileName = fileName + '.' + m_curSizeRollBackups;
}
}
return fileName;
}
#endregion
#region Initialize Options
/// <summary>
/// Determines curSizeRollBackups (only within the current roll point)
/// </summary>
private void DetermineCurSizeRollBackups()
{
m_curSizeRollBackups = 0;
string fullPath = null;
string fileName = null;
using(SecurityContext.Impersonate(this))
{
fullPath = System.IO.Path.GetFullPath(m_baseFileName);
fileName = System.IO.Path.GetFileName(fullPath);
}
ArrayList arrayFiles = GetExistingFiles(fullPath);
InitializeRollBackups(fileName, arrayFiles);
LogLog.Debug("RollingFileAppender: curSizeRollBackups starts at ["+m_curSizeRollBackups+"]");
}
/// <summary>
/// Generates a wildcard pattern that can be used to find all files
/// that are similar to the base file name.
/// </summary>
/// <param name="baseFileName"></param>
/// <returns></returns>
private static string GetWildcardPatternForFile(string baseFileName)
{
return baseFileName + '*';
}
/// <summary>
/// Builds a list of filenames for all files matching the base filename plus a file
/// pattern.
/// </summary>
/// <param name="baseFilePath"></param>
/// <returns></returns>
private ArrayList GetExistingFiles(string baseFilePath)
{
ArrayList alFiles = new ArrayList();
string directory = null;
using(SecurityContext.Impersonate(this))
{
string fullPath = Path.GetFullPath(baseFilePath);
directory = Path.GetDirectoryName(fullPath);
if (Directory.Exists(directory))
{
string baseFileName = Path.GetFileName(fullPath);
string[] files = Directory.GetFiles(directory, GetWildcardPatternForFile(baseFileName));
if (files != null)
{
for (int i = 0; i < files.Length; i++)
{
string curFileName = Path.GetFileName(files[i]);
if (curFileName.StartsWith(baseFileName))
{
alFiles.Add(curFileName);
}
}
}
}
}
LogLog.Debug("RollingFileAppender: Searched for existing files in ["+directory+"]");
return alFiles;
}
/// <summary>
/// Initiates a roll over if needed for crossing a date boundary since the last run.
/// </summary>
private void RollOverIfDateBoundaryCrossing()
{
if (m_staticLogFileName && m_rollDate)
{
if (FileExists(m_baseFileName))
{
DateTime last;
using(SecurityContext.Impersonate(this))
{
last = System.IO.File.GetLastWriteTime(m_baseFileName);
}
LogLog.Debug("RollingFileAppender: ["+last.ToString(m_datePattern,System.Globalization.DateTimeFormatInfo.InvariantInfo)+"] vs. ["+m_now.ToString(m_datePattern,System.Globalization.DateTimeFormatInfo.InvariantInfo)+"]");
if (!(last.ToString(m_datePattern,System.Globalization.DateTimeFormatInfo.InvariantInfo).Equals(m_now.ToString(m_datePattern, System.Globalization.DateTimeFormatInfo.InvariantInfo))))
{
m_scheduledFilename = m_baseFileName + last.ToString(m_datePattern, System.Globalization.DateTimeFormatInfo.InvariantInfo);
LogLog.Debug("RollingFileAppender: Initial roll over to ["+m_scheduledFilename+"]");
RollOverTime(false);
LogLog.Debug("RollingFileAppender: curSizeRollBackups after rollOver at ["+m_curSizeRollBackups+"]");
}
}
}
}
/// <summary>
/// Initializes based on existing conditions at time of <see cref="ActivateOptions"/>.
/// </summary>
/// <remarks>
/// <para>
/// Initializes based on existing conditions at time of <see cref="ActivateOptions"/>.
/// The following is done
/// <list type="bullet">
/// <item>determine curSizeRollBackups (only within the current roll point)</item>
/// <item>initiates a roll over if needed for crossing a date boundary since the last run.</item>
/// </list>
/// </para>
/// </remarks>
protected void ExistingInit()
{
DetermineCurSizeRollBackups();
RollOverIfDateBoundaryCrossing();
// If file exists and we are not appending then roll it out of the way
if (AppendToFile == false)
{
bool fileExists = false;
string fileName = GetNextOutputFileName(m_baseFileName);
using(SecurityContext.Impersonate(this))
{
fileExists = System.IO.File.Exists(fileName);
}
if (fileExists)
{
if (m_maxSizeRollBackups == 0)
{
LogLog.Debug("RollingFileAppender: Output file ["+fileName+"] already exists. MaxSizeRollBackups is 0; cannot roll. Overwriting existing file.");
}
else
{
LogLog.Debug("RollingFileAppender: Output file ["+fileName+"] already exists. Not appending to file. Rolling existing file out of the way.");
RollOverRenameFiles(fileName);
}
}
}
}
/// <summary>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -