Search code examples
c#asp.netasp.net-coreloggingnlog

How to config Nlog to delete log file after a month?


The log files after one month time need to be deleted.

Following is configurations in my Nlog.config file:

<target name="file" xsi:type="File" fileName="logs\${date:format=yyyy_MM}\${date:format=dd}.log" 
    layout="..." 
    
    archiveFileName="logs\archive\log.{#}.txt" <!-- actually I don't want to rename or move it -->
    archiveEvery="Month"
    maxArchiveFiles="1"
/>

How can I get it work?


Solution

  • NLog supports two archive-modes, but one should not be mixing them:

    • Dynamic FileName Archive Logic - Enabled by using fileName="${shortdate}.log". This means it will roll / archive dynamically because of the layout-renderer-logic.

    • Static FileName Archive Logic - Enabled by using archiveEvery="Month" and archiveFileName="...". This means it will expect the FileName to be static (Ex. fileName="app.log").

    NLog does not currently support archive-cleanup of sub-folders, so instead I suggest doing this:

    <target name="file" xsi:type="File" fileName="logs\${date:format=yyyy_MM_dd}.log" maxArchiveDays="31" />
    

    Alternative setup a scheduled task to run once a week that executes cleanup of old files, and also removes empty sub-folders.