Search code examples
c#loggingfilenamesnlog

Nlog fixed file name per app session


I am using Nlog to log from my c# app. The following is the <targets> section from my Nlog.config:

<targets>
    <target name="logfile" xsi:type="File" fileName="..\logs\${date:format=yyyyMMdd_HHmmss}_trg.log"
    layout="${counter} | ${date:format=yyyy-MM-dd HH\:mm\:ss.ffff} | ${machinename} | ${level:uppercase=true} | ${logger:shortName=true} | ${stacktrace} | ${message:exceptionSeparator=EXCEPTION:withException=true}" 
    keepFileOpen="true"/>
</targets>

For the filename I am using ${date:format=yyyyMMdd_HHmmss}_trg.log to name the log based on when it was created. However, while my app runs, the logger creates a new log file every second. How can I force Nlog to fix the file name and create only one log per session?


Solution

  • Apparently there is a ${cached} layout renderer that will render the layout once and reuse it. https://github.com/nlog/nlog/wiki/Cached-Layout-Renderer

    However, thanks to @wageoghe for your input. Your solution using the GlobalDiagnosticContext got me thinking about passing other values to NLog.config.