NLog - delete logs older than X days

piotrbalut picture piotrbalut · Aug 18, 2015 · Viewed 14.2k times · Source

How I can delete files with logs older than X days. It's simple, but I have in one folder logs only from one day. My NLog.config looks like:

<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" autoReload="true">
  <extensions>
    <add assembly="NLog.Extended" />
  </extensions>
  <variable name="LogHome" value="PATH"/>
  <variable name="DailyDir" value="${LogHome}${date:format=yyyy}/${date:format=MM}/${date:format=dd}/"/>
  <targets>
    <target name="asyncFile" xsi:type="AsyncWrapper">
      <target
        name="fatalLog"
        xsi:type="File"
        layout="${longdate}|${callsite}|${message}|${exception}"
        fileName="${DailyDir}/Fatal.txt"
              />
    </target>
    <target name="asyncFile" xsi:type="AsyncWrapper">
      <target
        name="errorLog"
        xsi:type="File"
        layout="${longdate}|${callsite}|${message}|${exception}"
        fileName="${DailyDir}/Error.txt"
              />
    </target>
  </targets>
  <rules>
    <logger name="*" level="Fatal" writeTo="fatalLog" />
    <logger name="*" level="Error" writeTo="errorLog" />
  </rules>
</nlog>

Answer

Dirk Trilsbeek picture Dirk Trilsbeek · Aug 18, 2015

right now you are creating logs in directories containing the date. To enable NLog to automatically manage your current and old log files, you need to use the NLog archiving functionality. As documented in the NLog file target documentation here you can use the attributes archiveFileName and maxArchiveFiles together with a daily log to keep log files for X days before NLog removes them.

You probably have to keep all archived logs in a single directory, otherwise NLog won't be able to locate the older logs and delete them. I would create an archive directory as a subdirectory of your main logging directory, have NLog put all archive logs there and then just use the maxArchiveFiles parameter to tell NLog how many of those logs you want to keep.

<targets>
<target name="asyncFile" xsi:type="AsyncWrapper">
  <target
    name="fatalLog"
    xsi:type="File"
    layout="${longdate}|${callsite}|${message}|${exception}"
    fileName="${LogHome}/Fatal.txt"
    archiveFileName="${LogHome}/Archive/Fatal-${shortdate}.txt"
    maxArchiveFiles="5"
    archiveEvery="Day"
          />
</target>
<target name="asyncFile" xsi:type="AsyncWrapper">
  <target
    name="errorLog"
    xsi:type="File"
    layout="${longdate}|${callsite}|${message}|${exception}"
    fileName="${LogHome}/Error.txt"
    archiveFileName="${LogHome}/Archive/Error-${shortdate}.txt"
    maxArchiveFiles="5"
    archiveEvery="Day"
          />
</target>
</targets>

that should give you two log files with the current log and an archive directory with 5 logs for each target from the last 5 days.