log4net - Remove old files rolling by date

后端 未结 3 1321
生来不讨喜
生来不讨喜 2020-12-28 08:44

INTENT:

a) I want my logs to be rolled by date in following file format yyyy-MM-dd.txt.

b) Additionally to this I want to remove old files which are out of

3条回答
  •  不思量自难忘°
    2020-12-28 09:02

    Considering that more than a decade went by and it's still not supported, I opted for the following solution of overriding RollingFileAppender with the required functionality:

    public class RollingDateAppender : RollingFileAppender {
      public TimeSpan MaxAgeRollBackups { get; set; }
    
      public RollingDateAppender()
        : base() {
        PreserveLogFileNameExtension = true;
        StaticLogFileName = false;
      }
    
      protected override void AdjustFileBeforeAppend() {
        base.AdjustFileBeforeAppend();
    
        string LogFolder = Path.GetDirectoryName(File);
        var CheckTime = DateTime.Now.Subtract(MaxAgeRollBackups);
        foreach (string file in Directory.GetFiles(LogFolder, "*.log")) {
          if (System.IO.File.GetLastWriteTime(file) < CheckTime)
            DeleteFile(file);
        }
      }
    
    }
    

    Configuration is just as simple as with the original class:

    roller = new RollingDateAppender {
      AppendToFile = true,
      File = ...;
      MaxAgeRollBackups = TimeSpan.FromDays(7),
      RollingStyle = RollingFileAppender.RollingMode.Date,
      ...
    };
    roller.ActivateOptions();
    BasicConfigurator.Configure(roller);
    

    Note that looking for *.log files in the log directory only makes sense if PreserveLogFileNameExtension is used or the DatePattern is used to include the extension at the end of the filename. If you need a different naming scheme, modify these in sync.

    (I used version 2.0.8 of log4net, earlier versions might not allow the necessary function to be overridden.)

提交回复
热议问题