Search code examples
c#nlog

c# NLog how to get only one logfile with the longdate as filename


Hello I am using for my console application NLog for logging. With that being said I would like to log everything that happens in the console using NLog to set that up I am using the NLOG.config:

  <target name="FullCSVFile" xsi:type="File"  fileName="logs\internal_${date:format=yyyyMMdd_HHmmss}.log" keepFileOpen="true">
  <layout xsi:type="CsvLayout">
    <column name="Console" layout="${message}" />
    <column name="Error" layout="${exception:format=ToString}" />
  </layout>
</target>

<logger minlevel="Debug" name="*" writeTo="FullCSVFile" />

But this way the tool makes a new file every second passed in the console, but I want to make one file when the tool starts with that timestamp and write everything in this one. How would I do that?


Solution

  • The trick is to use the ambient property cached=true like this:

    <target name="FullCSVFile" xsi:type="File"  fileName="logs\internal_${date:format=yyyyMMdd_HHmmss:cached=true}.log" keepFileOpen="true">
      <layout xsi:type="CsvLayout">
        <column name="Console" layout="${message}" />
        <column name="Error" layout="${exception:format=ToString}" />
      </layout>
    </target>
    

    It will make layout render once, and then just return the same cached value.

    See also: https://github.com/nlog/NLog/wiki/Cached-Layout-Renderer

    To make it "perfect" then you could use ${processinfo:StartTime:format=yyyyMMdd_HHmmss:cached=true} then the timestamp would be stable even after reloading NLog-config.