configurationnlog

How to create new log file for each application run


As the title implies how can I create a new log file for each application run ? I know how to do it for minute/hour/etc. but not for app. run

There is what I have for now:

target name="Debug" archiveEvery="Hour"
archiveFileName="${basedir}/logs/Debug.{#####}.txt" maxArchiveFiles="4" 
archiveNumbering="Sequence" xsi:type="File" fileName="${basedir}/logs/Debug.txt" 
layout="${date:format=HH\:mm\:ss} | ${level} | ${message} ${exception}
${exception:format=stacktrace}"

But actually I dont need to archive every hour, what I want is to archive every time when I run my app. There is what I found in old forum, but I dont know how to use Cached_layout_renderer


Solution

  • Most of the answers do not explain how and why it works.
    My solution:

    <target name="log"
       xsi:type="File"
       fileName="${basedir}/logs/log.${longdate:cached=true}.log"
       layout="${message}"
       archiveFileName="${basedir}/logs/archives/log.${shortdate}.{#}.log"
       archiveAboveSize="5242880"
       archiveEvery="Day"
       archiveNumbering = "Rolling"
       maxArchiveFiles="20" 
       />
    

    Explanation

    You have to use both the Cached Layout Renderer and the longdate variable. To understand why this works, you need to understand how they they work, and how they interact.

    longdate:

    fileName="${basedir}/logs/log.${longdate}.log"
    

    Using the longdate variable in your log name will pretty much guarantee a new log file on every execution... except it creates a new log file every millisecond even during a single execution which is probably not desirable except in the most rare of circumstances.

    Cached Layout Renderer:

    fileName="${basedir}/logs/log.${shortdate:cached=true}.log"
    

    Cached layout renderer will cache the variable on the first log call, and then always use that value for subsequent entries... but the cache only persists until the execution completes. Using shortdate, or any other variable that isn't guaranteed to changeon each execution, won't work. It will find a log file with the same filename it wants to use, and it'll just append (or delete if you have that set). This is not what we want.

    Combined:

    fileName="${basedir}/logs/log.${longdate:cached=true}.log"
    

    This works because it takes the millisecond timestamp of the first log per execution, and then caches it, and always uses that logfile until the execution terminates (clearing the cache). Next time you run it (unless it's the same millisecond... unlikely!) you'll get a new value cached, and a new log file (but only one!).