我具有以下配置,但是我找不到任何有关如何设置日期滚动样式的最大备份文件的文档。我知道您可以通过使用maxSizeRollBackups使用大小滚动样式来做到这一点。
1 2 3 4 5 6 7 8 9
| <file value="mylog.log" />
<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> |
你不能。
来自
log4net SDK参考
RollingFileAppender类
CAUTION
A maximum number of backup files when rolling on date/time boundaries is not supported.
即使不支持它,这也是我处理这种情况的方法:
这是我的配置:
1 2 3 4 5 6 7 8 9 10
| <file value="C:\\logs\\LoggingTest\\logfile.txt" />
<rollingStyle value="Composite" />
<datePattern value="yyyyMMdd" />
<maxSizeRollBackups value="10" />
<maximumFileSize value="1MB" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%date - %message%newline" />
</layout>
</appender> |
在应用程序启动时,我会做:
1 2 3 4
| XmlConfigurator.Configure();
var date = DateTime.Now.AddDays(-10);
var task = new LogFileCleanupTask();
task.CleanUp(date); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77
| 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 -
/// <summary>
/// Cleans up. Auto configures the cleanup based on the log4net configuration
/// </summary>
/// <param name="date">Anything prior will not be kept.</param>
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);
}
}
/// <summary>
/// Cleans up.
/// </summary>
/// <param name="logDirectory">The log directory.</param>
/// <param name="logPrefix">The log prefix. Example: logfile dont include the file extension.</param>
/// <param name="date">Anything prior will not be kept.</param>
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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| /// <summary>
/// Extension helper methods for strings
/// </summary>
[DebuggerStepThrough, DebuggerNonUserCode]
public static class StringExtensions
{
/// <summary>
/// Formats a string using the <paramref name="format"/> and <paramref name="args"/>.
/// </summary>
/// <param name="format">The format.</param>
/// <param name="args">The args.</param>
/// <returns>A string with the format placeholders replaced by the args.</returns>
public static string Sub(this string format, params object[] args)
{
return string.Format(format, args);
}
} |
几个月前,我花了一些时间研究这个问题。 v1.2.10不支持根据日期滚动删除较旧的日志文件。在下一个版本的任务列表中。我获取了源代码,并亲自添加了功能,如果有兴趣,可以将其发布给其他人。可以在https://issues.apache.org/jira/browse/LOG4NET-27中找到该问题和补丁。
要限制日志数量,请在日期模式中不要包括年份或月份,例如datePattern value =" _ dd'.log'"
这将每天创建一个新日志,下个月将被覆盖。
最近,当我尝试根据传递到我的服务中的maxAgeInDays配置值来清理日志时,遇到了这种需求...正如我之前许多人一样,我开始接触NTFS"功能"隧道,这使得使用FileInfo .CreationDate有问题(尽管我也自那时以来一直在解决此问题)...
因为我有一个模式可以使用,所以我决定只使用自己的清理方法...我的记录器是通过编程配置的,因此我只在记录器设置完成后才调用以下内容...
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| //.........................
//Log Config Stuff Above...
log4net.Config.BasicConfigurator.Configure(fileAppender);
if(logConfig.DaysToKeep > 0)
CleanupLogs(logConfig.LogFilePath, logConfig.DaysToKeep);
}
static void CleanupLogs(string logPath, int maxAgeInDays)
{
if (File.Exists(logPath))
{
var datePattern ="yyyy.MM.dd";
List<string> logPatternsToKeep = new List<string>();
for (var i = 0; i <= maxAgeInDays; i++)
{
logPatternsToKeep.Add(DateTime.Now.AddDays(-i).ToString(datePattern));
}
FileInfo fi = new FileInfo(logPath);
var logFiles = fi.Directory.GetFiles(fi.Name +"*")
.Where(x => logPatternsToKeep.All(y => !x.Name.Contains(y) && x.Name != fi.Name));
foreach (var log in logFiles)
{
if (File.Exists(log.FullName)) File.Delete(log.FullName);
}
}
} |
可能不是最漂亮的方法,但是对于我们的目的来说效果很好...
不确定确切需要什么。以下是我的lo4net.config文件之一的摘录:
1 2 3 4 5 6 7 8 9 10
| <param name="File" value="App_Data\\log"/>
<param name="DatePattern" value=".yyyy-MM-dd-tt".log""/>
<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> |
NLog,其设置与Log4Net(
从log4net追加器继承并添加自己的覆盖方法(执行文件清除)非常容易。我覆盖了OpenFile来做到这一点。这是一个自定义log4net附加程序的示例,可帮助您入门:https://stackoverflow.com/a/2385874/74585