log4net One file per execution by date

Friday, December 18, 2009
by asalvo

I have been a big fan of log4net for the past several years. It’s a light weight, reliable, open source logging platform. Today I needed to create FileAppender that created a log file that had the current date in ISO 8601 format.

After playing around with various options for the RollingFileAppender, I finally figured out the correct way to accomplish my goal. By adding the type="log4net.Util.PatternString" to the file element in configuration file, you can change the name of the log file at runtime based on properties within log4net. It just so happens, that one of the properties is the current date and time.

Here is my appender that I ended up with:

<appender name="MyAppender" type="log4net.Appender.FileAppender">  
  <file type="log4net.Util.PatternString" value="logs%date{yyyyMMddTHHmmss}.txt" />  
  <appendToFile value="true"/>  
  <layout type="log4net.Layout.PatternLayout">  
    <conversionPattern value="%date %-5level %logger &#8211; %message%newline"/>  
  </layout>   
</appender>

Comments

comments powered by Disqus