即使它不受支持,这也是我处理这种情况的方法:
这是我的配置:
<appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="C:\logs\LoggingTest\logfile.txt" />
<appendToFile value="true" />
<rollingStyle value="Composite" />
<datePattern value="yyyyMMdd" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="1MB" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date - %message%newline" />
</layout>
</appender>
在应用程序启动时,我这样做:
XmlConfigurator.Configure();
var date = DateTime.Now.AddDays(-10);
var task = new LogFileCleanupTask();
task.CleanUp(date);
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using log4net;
using log4net.Appender;
using log4net.Config;
public class LogFileCleanupTask
{
#region - Constructor -
public LogFileCleanupTask()
{
}
#endregion
#region - Methods -
public void CleanUp(DateTime date)
{
string directory = string.Empty;
string filePrefix = string.Empty;
var repo = LogManager.GetAllRepositories().FirstOrDefault(); ;
if (repo == null)
throw new NotSupportedException("Log4Net has not been configured yet.");
var app = repo.GetAppenders().Where(x => x.GetType() == typeof(RollingFileAppender)).FirstOrDefault();
if (app != null)
{
var appender = app as RollingFileAppender;
directory = Path.GetDirectoryName(appender.File);
filePrefix = Path.GetFileName(appender.File);
CleanUp(directory, filePrefix, date);
}
}
public void CleanUp(string logDirectory, string logPrefix, DateTime date)
{
if (string.IsNullOrEmpty(logDirectory))
throw new ArgumentException("logDirectory is missing");
if (string.IsNullOrEmpty(logPrefix))
throw new ArgumentException("logPrefix is missing");
var dirInfo = new DirectoryInfo(logDirectory);
if (!dirInfo.Exists)
return;
var fileInfos = dirInfo.GetFiles("{0}*.*".Sub(logPrefix));
if (fileInfos.Length == 0)
return;
foreach (var info in fileInfos)
{
if (info.CreationTime < date)
{
info.Delete();
}
}
}
#endregion
}
Sub方法是一种扩展方法,它基本上像这样包装string.format:
[DebuggerStepThrough, DebuggerNonUserCode]
public static class StringExtensions
{
public static string Sub(this string format, params object[] args)
{
return string.Format(format, args);
}
}