NLog - delete logs older than X days

NLog 4.5 makes it easier to setup archive cleanup:

  <target
    name="errorLog"
    xsi:type="File"
    layout="${longdate}|${callsite}|${message}|${exception}"
    fileName="${DailyDir}/Error.${shortdate}.txt"
    maxArchiveFiles="5"
  />

NLog 4.7 also introduces the setting maxArchiveDays (Useful if also using archiveAboveSize). See also: https://github.com/NLog/NLog/wiki/File-target#archive-old-log-files


<target name="Logs" xsi:type="File" fileName="${basedir}/Logs/${shortdate}/${shortdate}-${level}.csv" archiveAboveSize="10240" keepFileOpen="false" 
        maxArchiveDays="30" maxArchiveFiles="90">
  <layout xsi:type="CSVLayout">
    <column name="time" layout="${longdate}" />
    <column name="logger" layout="${logger}"/>
    <column name="message" layout="${message}" />
  </layout>
</target>

I used the above code in my targets to overcome this problem. It will create a new file if the file increase 10MB and storing as CSV so it's easy to read in excel and deleting files 30 days old.


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.