Log4Net: set Max backup files on RollingFileAppender with rolling Date

Viewed 75101

I have the following configuration, but I have not able to find any documentation on how to set a maximum backup files on date rolling style. I know that you can do this with size rolling style by using the maxSizeRollBackups.

<appender name="AppLogFileAppender" type="log4net.Appender.RollingFileAppender">
    <file value="mylog.log" />
    <appendToFile value="true" />
    <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
    <rollingStyle value="Date" />
    <datePattern value=".yyMMdd.'log'" />
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%d %-5p %c - %m%n"  />
    </layout>
</appender>
9 Answers

I spent some time looking into this a few months ago. v1.2.10 doesn't support deleting older log files based on rolling by date. It is on the task list for the next release. I took the source code and added the functionality myself, and posted it for others if they are interested. The issue and the patch can be found at https://issues.apache.org/jira/browse/LOG4NET-27 .

Not sure exactly what you need. Below is an extract from one of my lo4net.config files:

  <appender name="RollingFile" type="log4net.Appender.RollingFileAppender">
    <param name="File" value="App_Data\log"/>
    <param name="DatePattern" value=".yyyy-MM-dd-tt&quot;.log&quot;"/>
    <param name="AppendToFile" value="true"/>
    <param name="RollingStyle" value="Date"/>
    <param name="StaticLogFileName" value="false"/>
    <param name="maxSizeRollBackups" value="60" />
    <layout type="log4net.Layout.PatternLayout">
      <param name="ConversionPattern" value="%r %d [%t] %-5p %c - %m%n"/>
    </layout>
  </appender>

Stopped worrying about a more complex x per date and just specified and arbitrary file count and just sort of threw this one together. Be careful with the [SecurityAction.Demand].

public string LogPath { get; set; }
public int MaxFileCount { get; set; } = 10;

private FileSystemWatcher _fileSystemWatcher;

[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
public async Task StartAsync()
{
    await Task.Yield();

    if (!Directory.Exists(LogPath))
    { Directory.CreateDirectory(LogPath); }

    _fileSystemWatcher = new FileSystemWatcher
    {
        Filter = "*.*",
        Path = LogPath,
        EnableRaisingEvents = true,
        NotifyFilter = NotifyFilters.FileName
            | NotifyFilters.LastAccess
            | NotifyFilters.LastWrite
            | NotifyFilters.Security
            | NotifyFilters.Size
    };

    _fileSystemWatcher.Created += OnCreated;
}

public async Task StopAsync()
{
    await Task.Yield();

    _fileSystemWatcher.Created -= OnCreated; // prevents a resource / memory leak.
    _fileSystemWatcher = null; // not using dispose allows us to re-start if necessary.
}

private void OnCreated(object sender, FileSystemEventArgs e)
{
    var fileInfos = Directory
        .GetFiles(LogPath)
        .Select(filePath => new FileInfo(filePath))
        .OrderBy(fileInfo => fileInfo.LastWriteTime)
        .ToArray();

    if (fileInfos.Length <= MaxFileCount)
    { return; }

    // For every file (over MaxFileCount) delete, starting with the oldest file.
    for (var i = 0; i < fileInfos.Length - MaxFileCount; i++)
    {
        try
        {
            fileInfos[i].Delete();
        }
        catch (Exception ex)
        {
            /* Handle */
        }
    }
}
Related