Log4net - Create new log file each time application is started

Sandeep picture Sandeep · Jun 13, 2011 · Viewed 7k times · Source

Can we create separate log files each time when the application is run? If i run my application 2 times, I should get 2 separate log files, hopefully the file names can be appended with the created dateTime

eg:
log_0830 - when application is run on 8:30 am
log_2130 - when application is run on 9:30 pm

Answer

Tschareck picture Tschareck · Jul 2, 2012

Put that into your app.config:

 <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
 </configSections>
 <log4net>
    <appender name="file" type="log4net.Appender.RollingFileAppender">
      <file value="log_"/>
      <rollingStyle value="Date"/>
      <datePattern value="HHmm.\tx\t"/>
      <staticLogFileName value="false"/>
      <appendToFile value="true" />
      <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date %-5level %message%newline" />
      </layout>      
    </appender>
    <root>
      <level value="ALL"/>
      <appender-ref ref="file"/>
    </root>
  </log4net>

That configuration would produce filenames:
log_0830.txt - when application is run on 8:30 am
log_2130.txt - when application is run on 9:30 pm