Delete log files after x days

Freddy picture Freddy · Apr 6, 2011 · Viewed 29.5k times · Source

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?

Answer

ccellar picture ccellar · Aug 3, 2011

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