我有以下配置,但我无法找到有关如何在日期滚动样式上设置最大备份文件的任何文档。我知道你可以使用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>
答案 0 :(得分:44)
答案 1 :(得分:37)
即使它不受支持,这是我处理这种情况的方式:
这是我的配置:
<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 -
/// <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,如下所示:
/// <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);
}
}
答案 2 :(得分:11)
答案 3 :(得分:7)
要限制日志数量,请不要在日期模式中包含年份或月份,例如。 datePattern value =&#34; _dd&#39; .log&#39;&#34;
这将每天创建一个新日志,并在下个月被覆盖。
答案 4 :(得分:2)
不确定您需要什么。以下是我的一个lo4net.config文件的摘录:
<appender name="RollingFile" type="log4net.Appender.RollingFileAppender">
<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>
答案 5 :(得分:1)
我最近在尝试根据传递到我的服务中的maxAgeInDays配置值清理日志日志时遇到了这种需求......正如我之前所遇到的那样,我接触到了NTFS&#39;功能&#39;隧道,这使得使用FileInfo.CreationDate有问题(虽然我已经解决了这个问题)......
由于我有一个模式,我决定只使用自己的清理方法...我的记录器是以编程方式配置的,所以我只需在记录器设置完成后调用以下内容...
//.........................
//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);
}
}
}
可能不是最漂亮的方法,但为我们的目的工作得很好......
答案 6 :(得分:1)
NLog,其设置方式与Log4Net几乎相同(并且主动维护 - 甚至支持.NET Core),支持基于日期滚动日志。
答案 7 :(得分:0)
从log4net appender继承并添加说你自己的覆盖方法来执行文件的清理是相当容易的。我重写OpenFile来做这件事。以下是一个自定义log4net appender示例,可帮助您入门:https://stackoverflow.com/a/2385874/74585