x 天后删除日志文件

发布于 2024-10-30 17:34:50 字数 178 浏览 5 评论 0原文

我想使用 Nlog 使用文件目标进行日志 示例。如何在X天后删除文件而不存档它们?或者是否可以将文件存档到同一文件夹?

I would like to log with Nlog using the file target like in this example. How can I realize a deletion of the files after X days without archiving them? Or is it possible to archive the files to the same folder?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(7

长亭外,古道边 2024-11-06 17:34:50

您可以简单地使用内置的归档功能。除了当前日志之外,此设置还将保留 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>

另请参阅文件目标的文档

You could simply use the built-in archiving functionality. This setting will keep 7 old log files in addition to your current log. The cleanup is done by NLog automatically.

<?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>

See also the documentation of the file target

远山浅 2024-11-06 17:34:50

我发现,如果我归档日志文件名中带有日期戳的文件,归档日志会变得混乱,并且 {#} 始终转换为“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", ...);

I found that if I archive files with date-stamps in the log filenames, the archive log gets confused and {#} always translates to "0" causing old logs to never get deleted. Also, if I use a GDC reference in the log filename, it doesn't switch logs at all.

I now have to manually delete old logs if I want these fancy log filenames. The fact that they have the date in the filename causes them to automatically switch files.

// 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 target:

 filename="${environment:variable=HOMEDRIVE}${environment:variable=HOMEPATH}\logs\log-${gdc:item=MySpecialId}-${date:format=yyyyMMdd}.txt"
GDC.Set("MySpecialId", ...);
梦在夏天 2024-11-06 17:34:50

我不知道这是否能回答您的问题,但看起来 maxArchiveFiles 应该可以满足您的要求。我自己实际上并没有使用过这个选项,所以我不能确定。您当然可以将日志文件“存档”在同一文件夹中。

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

尝试归档文件命名模板。使用 archiveNumbering 选项可以让您对存档文件的编号方式进行一定程度的控制。

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

I don't know if this answers your question, but it looks like the maxArchiveFiles should do what you want. I have not actually used this option myself, so I can't say for sure. You can certainly "archive" your log files in the same folder.

If it were me, I would make a very small program that does some logging and set the time (archiveEvery="minute") so that it is easy to force the archiving logic to kick in. Set maxArchiveFiles to something like 5 and see if NLog keeps only 5 log files. Run your program for a while, maybe generating log messages via a timer so you can easily space the log messages over enough time that NLog's archiving/rolling logic kicks in.

Experiment with the archive file naming template. Using the archiveNumbering option gives you some control over how the archive files are numbered.

Sorry I could not give a more definitive answer or a concrete example, but I have not used those options either, so I would just have to do the same experiment(s) and I am pressed for time right now.

爺獨霸怡葒院 2024-11-06 17:34:50

您可以使用当天的名称并将 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" />   

You can use the name of the day and set the maxArchiveFiles to a fixed number. For example, foreach day of the week you could store a max of 100 files of 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" />   
尸血腥色 2024-11-06 17:34:50
     //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();
            }

        }
     //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();
            }

        }
驱逐舰岛风号 2024-11-06 17:34:50

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结合使用时很有用。

NLog 4.5 (or newer) makes it much easier to setup archive. You just configure fileName and maxArchiveFiles:

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

See also: https://github.com/NLog/NLog/wiki/File-target#archive-old-log-files

NLog 4.7 (or newer) introduces the new option maxArchiveDays that inspects the actual timestamp of the log-files. Useful when combined with archiveAboveSize.

捂风挽笑 2024-11-06 17:34:50

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"
            />```


From NLog 4.5 (or newer) you can use the following if you want deletion after 7 days, but also a limited used space per day, 700MB in our example:

Be careful that in the case limit size is reached in archive folder you will find the most recent logs, not necessary the ones from the last 7 days.This happens because the options are mutual exclusive.

<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"
            />```


~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文