【问题标题】:Delete log files after x daysx 天后删除日志文件
【发布时间】:2011-07-30 18:02:33
【问题描述】:

我想使用 example 中的文件目标使用 Nlog 登录。如何在X 天后删除文件而不归档它们?或者是否可以将文件归档到同一个文件夹?

【问题讨论】:

  • 请将其中一项标记为答案。

标签: logging archive nlog


【解决方案1】:

您可以简单地使用内置的归档功能。除了您当前的日志之外,此设置还将保留 7 个旧日志文件。清理由 NLog 自动完成。

<?xml version="1.0" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

    <targets>
        <target name="file" xsi:type="File"
            layout="${longdate} ${logger} ${message}" 
            fileName="${basedir}/logs/logfile.txt" 
            archiveFileName="${basedir}/logs/log.{#}.txt"
            archiveEvery="Day"
            archiveNumbering="Rolling"
            maxArchiveFiles="7"
            concurrentWrites="true" />
    </targets>

    <rules>
        <logger name="*" minlevel="Debug" writeTo="file" />
    </rules>
</nlog>

另请参阅file target 的文档

【讨论】:

  • 如果我使用archiveAboveSize会发生什么?这将不再起作用,因为如果我一天有 7 个文件,它将删除所有其余文件。有解决办法吗?
  • @UriAbramson 恕我直言,这些是互斥设置。
  • @ccellar 我知道这是旧的,但现在你有:archiveNumbering="DateAndSequence"
  • @ccellar 我想将此添加到 SO 文档中,但我确实需要一些投票:stackoverflow.com/documentation/nlog/commit。你能帮忙吗?
  • 酷!谢谢!
【解决方案2】:

我发现如果我在日志文件名中归档带有日期戳的文件,归档日志会变得混乱,{#} 总是转换为“0”,导致旧日志永远不会被删除。另外,如果我在日志文件名中使用 GDC 引用,它根本不会切换日志。

如果我想要这些花哨的日志文件名,我现在必须手动删除旧日志。他们在文件名中包含日期这一事实导致他们自动切换文件。

// Delete log files older than X days

var dirInfo = new DirectoryInfo(".");
var oldestArchiveDate = DateTime.Now - new TimeSpan(30, 0, 0, 0);
foreach (FileInfo fi in dirInfo.GetFiles())
    if (fi.Name.StartsWith("log-") && fi.Name.EndsWith(".txt") && fi.CreationTime < oldestArchiveDate)
        fi.Delete();

var midnight = DateTime.Today.AddDays(1);
_oldLogCleanUpThread = new System.Threading.Timer(OldLogCleanUpThreadMethod, null, midnight - DateTime.Now, TimeSpan.FromDays(1));

nlog 目标:

 filename="${environment:variable=HOMEDRIVE}${environment:variable=HOMEPATH}\logs\log-${gdc:item=MySpecialId}-${date:format=yyyyMMdd}.txt"
GDC.Set("MySpecialId", ...);

【讨论】:

    【解决方案3】:

    我不知道这是否回答了您的问题,但看起来maxArchiveFiles 应该可以满足您的需求。我自己并没有真正使用过这个选项,所以我不能肯定地说。您当然可以将日志文件“归档”到同一文件夹中。

    如果是我,我会编写一个非常小的程序来执行一些日志记录并设置时间 (archiveEvery="minute"),以便很容易强制归档逻辑启动。将 maxArchiveFiles 设置为 5看看 NLog 是否只保留 5 个日志文件。运行您的程序一段时间,可能会通过计时器生成日志消息,这样您就可以轻松地将日志消息间隔足够长的时间,以便 NLog 的归档/滚动逻辑启动。

    使用存档文件命名模板进行实验。使用 archiveNumbering 选项可以让您对存档文件的编号方式进行一些控制。

    抱歉,我无法给出更明确的答案或具体示例,但我也没有使用这些选项,所以我只需要做同样的实验,我现在时间紧迫。

    【讨论】:

      【解决方案4】:

      您可以使用当天的名称并将maxArchiveFiles 设置为固定数字。例如,对于一周中的每一天,您最多可以存储 100 个 100Kb 的文件:

      <variable name="dayname" value="${date:format=dddd}" />
      
      <target name="logfile" xsi:type="File"
              fileName="${basedir}/Logs/MyLog_${dayname}.txt"
              archiveFileName="${basedir}/Logs/Archives/MyLog_${dayname}.{#####}.txt"
              archiveAboveSize="102400"
              archiveNumbering="Sequence"            
              maxArchiveFiles="100"
              concurrentWrites="true"
              keepFileOpen="false"
              encoding="iso-8859-2" />   
      

      【讨论】:

        【解决方案5】:
             //Store the number of days after which you want to delete the logs.
             int Days = 30;
        
             // Storing the path of the directory where the logs are stored.
             String DirPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase).Substring(6) + "\\Log(s)\\";
        
             //Fetching all the folders.
             String[] objSubDirectory = Directory.GetDirectories(DirPath);
        
             //For each folder fetching all the files and matching with date given 
             foreach (String subdir in objSubDirectory)     
                {
                    //Getting the path of the folder                 
                    String strpath = Path.GetFullPath(subdir);
                    //Fetching all the files from the folder.
                    String[] strFiles = Directory.GetFiles(strpath);
                    foreach (string files in strFiles)
                    {
                        //For each file checking the creation date with the current date.
                        FileInfo objFile = new FileInfo(files);
                        if (objFile.CreationTime <= DateTime.Now.AddDays(-Days))
                        {
                            //Delete the file.
                            objFile.Delete();
                        }
                    }
        
                    //If folder contains no file then delete the folder also.
                    if (Directory.GetFiles(strpath).Length == 0)
                    {
                        DirectoryInfo objSubDir = new DirectoryInfo(subdir);
                        //Delete the folder.
                        objSubDir.Delete();
                    }
        
                }
        

        【讨论】:

        • +1 在确定 NLog 可能没有所需的确切功能后,针对原始问题提出简单直接的解决方案,而不是变通方法。
        【解决方案6】:

        NLog 4.5(或更高版本)使设置存档变得更加容易。你只需配置fileNamemaxArchiveFiles

        <target name="logfile" type="File" fileName="Log-${shortdate}.txt" maxArchiveFiles="7" />
        

        另请参阅:https://github.com/NLog/NLog/wiki/File-target#archive-old-log-files

        NLog 4.7(或更高版本)引入了新选项maxArchiveDays,用于检查日志文件的实际时间戳。与archiveAboveSize 结合使用时很有用。

        【讨论】:

          【解决方案7】:

          NLog 4.5(或更高版本)开始,如果您想在 7 天后删除,您可以使用以下内容,但每天也可以使用有限的空间,在我们的示例中为 700MB:

          请注意,如果存档文件夹中达到限制大小,您将找到最新的日志,而不是过去 7 天的日志。这是因为选项是互斥的。

          <target xsi:type="File" name="f"
                      fileName="${basedir}/logs/$currentLogfile.log"
                      archiveFileName="${basedir}/logs/archives/logfile.{#}.log"
                      layout="${longdate} ${uppercase:${level}} ${message} ${exception:format=toString}"
                      archiveNumbering="DateAndSequence"
                      archiveEvery="Day"
                      archiveDateFormat="yyyyMMdd"
                      maxArchiveFiles="7"
                      archiveAboveSize="104857600"
                      />```
          
          
          

          【讨论】:

            猜你喜欢
            • 2020-03-11
            • 2013-06-22
            • 2023-04-07
            • 1970-01-01
            • 1970-01-01
            • 2011-02-15
            • 2016-12-24
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多