Wednesday, 3 August 2011

C# MVC3 Log4Net configuration

Add log4net section to top level Web.config
<configuration>
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />
  </configSections>
  [...]
  <log4net>
   <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
      <param name="File" value="Log\\MyProject.log" />
      <param name="AppendToFile" value="true" />
      <param name="RollingStyle" value="Size" />
      <param name="MaxSizeRollBackups" value="10" />
      <param name="MaximumFileSize" value="500KB" />
      <param name="StaticLogFileName" value="true" />
      <param name="Threshold" value="INFO"/>
      <layout type="log4net.Layout.PatternLayout">
        <param name="ConversionPattern" value="%d [%t] %-5p %c.%M():%L - %m%n" />
      </layout>
    </appender>
    <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
      <param name="Threshold" value="DEBUG"/>
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%d [%t] %-5p %c.%M():%L - %m%n" />
      </layout>
    </appender>
    <logger name="MyCompany">
      <appender-ref ref="RollingFileAppender" />      
      <appender-ref ref="ConsoleAppender" /> 
    </logger>
  </log4net>
</configuration>

Initialize log4net from Application_Start() method in Global.asax.cs

protected void Application_Start()
{
  [...]
  log4net.Config.XmlConfigurator.Configure();
}

Click here for more detailed post about Log4Net configuration in console apps

No comments:

Post a Comment