Having a log per day

swade1987 picture swade1987 · Apr 27, 2012 · Viewed 51k times · Source

Currently my application is using log4net to log errors, the web.config for this is as followed:

<log4net> 
    <appender name="FileAppender" type="log4net.Appender.FileAppender">
        <file value="c:/paypal/logs/gateway.log" />
        <appendToFile value="true" />
        <layout type="log4net.Layout.PatternLayout">
            <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] – %message%newline" />
        </layout>
    </appender>
    <root>
        <level value="DEBUG" />
        <appender-ref ref="FileAppender" />
    </root>
</log4net>

However, the problem with this is that everyday the logs always go to gateway.log

Does anybody know a way to have a different log file per day using log4net?

Ideally I don't want to have to manually edit the web.config every night using a scheduled task.

Answer

Sergey Berezovskiy picture Sergey Berezovskiy · Apr 27, 2012

You should use RollingFileAppender with rollingStyle Date and datePattern yyyyMMdd (this will roll every day).

Example of configuration:

<appender name="FileAppender" type="log4net.Appender.RollingFileAppender">
    <file value="c:/paypal/logs/gateway.log" />
    <appendToFile value="true" />
    <rollingStyle value="Date" />
    <datePattern value="yyyyMMdd" />
    <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] – %message%newline" />
    </layout>
</appender>

UPDATE: I think a better way is to include the date into file name. And use datePattern value only to show when new log file should be created.

<appender name="FileAppender" type="log4net.Appender.RollingFileAppender">
  <file type="log4net.Util.PatternString" value="c:/paypal/logs/gateway_%date{yyyyMMdd}.log" />
  <appendToFile value="true" />
  <rollingStyle value="Date" />
  <datePattern value="yyyyMMdd" />
  <layout type="log4net.Layout.PatternLayout">
    <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] – %message%newline" />
  </layout>
</appender>

In this case all your files will have name like gateway_20120427.log.