Log4net rolling file log based on date and file size

Logging is an important part of any application and a developer spends a good amount of time writing code to log. Logging is important as this helps us create a trace of all the events in the application and in turn helps in debugging, identifying and analyzing issues and bugs. Log4net is an open source framework for logging the output in an application. The application framework is released under Apache License, Version 2.0. Log4net provides multiple types of logging techniques.

What we are going to discuss today is how to configure log4net for a requirement I wanted to implement in one of my project? Requirement was to implement a rolling log system based on date and file size. i.e I wanted to implement a file logging, that would create a new log file everyday and if the file size extends a certain size it should create a new file.

To accomplish this, I used the “RollingFileAppender” for the type of appender. Let’s discuss the important parameters in the configuration.

  • PreserveLogFileNameExtension – This parameter indicates if the file extension of the log files should be preserved during rolling.
  • rollingStyle – Rolling criteria to use for log, I used Composite to roll based on date and size of the log.
  • datePattern – Date pattern to append to the log file name, I configured this as _MMddyyyy.
  • maxSizeRollBackups – Maximum number of log files to keep before deleting during rolling.
  • maximumFileSize – Maximum size of the log file before it is rolled to new file.
  • staticLogFileName – Indicates whether to always log in the same file, I set this to true.

For the component to read the parameter from the config file. We to add the following code.

XmlConfigurator.Configure();
or
[assembly: log4net.Config.XmlConfigurator(Watch=false)]

The parameters used in the configuration are given below.

<log4net>
  <appender name="RollingLogFile" type="log4net.Appender.RollingFileAppender">
    <file value="log.log" />
    <PreserveLogFileNameExtension value="true"/>
    <appendToFile value="false" />
    <rollingStyle value="Composite"/>
    <datePattern value="_MMddyyyy"/>
    <maxSizeRollBackups value="2"/>
    <maximumFileSize value="10KB"/>
    <staticLogFileName value="true" />
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" />
    </layout>
  </appender>
  <root>
    <appender-ref ref="RollingLogFile" />
  </root>
</log4net>

The sample code with the configuration and code used to test the rolling log is available in the below repository
Sample Code: https://github.com/rbipin/RollingLog_Log4net

Site Footer