75

我有以下配置,但我找不到任何关于如何设置日期滚动样式的最大备份文件的文档。我知道您可以通过使用 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>
4

9 答案 9

53

你不能。

来自 log4net SDK 参考
RollingFileAppender 类

警告

不支持在日期/时间边界滚动时的最大备份文件数。

于 2008-09-18T22:26:14.183 回答
42

即使它不受支持,以下是我处理这种情况的方法:

这是我的配置:

    <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);
    }
}
于 2010-05-26T20:40:36.617 回答
12

要限制日志的数量,请不要在日期模式中包含年份或月份,例如 datePattern value="_dd'.log'"

这将每天创建一个新日志,并在下个月被覆盖。

于 2016-06-07T12:19:49.997 回答
11

几个月前我花了一些时间研究这个。v1.2.10 不支持根据日期滚动删除较旧的日志文件。它在下一个版本的任务列表中。我自己拿了源代码并添加了功能,如果他们有兴趣,我会把它发布给其他人。问题和补丁可以在https://issues.apache.org/jira/browse/LOG4NET-27找到。

于 2010-03-12T17:40:51.990 回答
3

不确定你到底需要什么。以下是我的 lo4net.config 文件之一的摘录:

  <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>
于 2008-09-18T18:32:47.770 回答
2

我最近在尝试根据传递给我的服务的 maxAgeInDays 配置值清理日志日志时遇到了这种需求......正如我之前的许多人一样,我接触到了 NTFS“功能”隧道,这使得使用 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);
        }
    }
}

可能不是最漂亮的方法,但对于我们的目的来说工作得很好......

于 2013-03-12T15:09:40.020 回答
1

NLog的设置方式与 Log4Net 几乎相同(并且得到了积极维护——甚至支持 .NET Core),支持基于日期的滚动日志。

于 2017-01-09T21:22:59.900 回答
0

从 log4net appender 继承并添加你自己的覆盖方法来执行文件清理是相当容易的。我覆盖了 OpenFile 来执行此操作。这是一个自定义 log4net 附加程序的示例,可帮助您入门:https ://stackoverflow.com/a/2385874/74585

于 2012-09-27T02:35:50.790 回答
0

不再担心每个日期更复杂的 x 以及只是指定和任意文件计数,只是将这个放在一起。小心[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 */
        }
    }
}
于 2021-12-17T16:48:54.013 回答