Mar 20, 2013

Proper configuring Log4Net in ASP.NET in separate file

There is a lot on net about Log4Net but still this fantastic tool falls in category "setup initially and forget".
This means that after you once configure it you forget is there for months and just use its fluent logging capabilities.
Hence on project kick off I tend to always spend time looking for proper way to configure it and sometimes run into questions.

Here goes recipe for configuring Log4Net for ASP.NET 4.5 MVC hosted in Visual Studio Development server.

  1. First use NuGet and install Log4Net for your project.
  2. For Web only! This is not necessary for Desktop when you execute 8.!
    In your web.config configsections register Log4Net section:
<configSections>
...

    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, 
log4net"/>
...

  </configSections>

3. For Web applications create log4net.xml and reference it as in 4. as standalone Log4Net config file.
For desktop create log4net.Config and reference it using assembly reference (see 8.)  Here is simple example:

<?xml version="1.0"?>
<log4net>
  <appender name="FileAppender" type="log4net.Appender.RollingFileAppender">
    <param name="File" value="log4net_applog.log" />
    <param name="DatePattern" value="yyyy.MM.dd" />
    <param name="RollingStyle" value="Size" />
    <param name="maxSizeRollBackups" value="10" />
    <param name="maximumFileSize" value="100KB" />
    <layout type="log4net.Layout.PatternLayout">
      <param name="ConversionPattern" value="
%date{yyyy-MM-dd HH:mm:ss ffff} [%-3t] %-5p %logger{1}.%method: %message%newline" />
    </layout>
  </appender>
  <root>
    <!-- OFF, FATAL, ERROR, WARN, DEBUG, INFO, ALL -->
    <level value="DEBUG" />
    <appender-ref ref="FileAppender" />
  </root>
</log4net>

4. Use this for WEB. In web.config  AppSettings section add reference to above Log4Net.xml:

  <appSettings>
...

  <add key="log4net.Config" value="log4net.xml" />   

...

5. Give write rights to folder in which log resides. This depends on your OS version. For Win 7 it is NETWORK SERVICE account. If you are using Local IIS then check in your IIS under which account runs your ASP.NET application pool.

6. In Global.asax.cs configure Log4Net instance as external:


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



7. In every class you wish to use log4net register log instance:



   private readonly ILog log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);


8. Use this for Desktop. Add this to your Assembly Properties file:
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "Log4Net.config", Watch = true)]
Attribute watch enables to change configuration on the fly without restarting app.

9. If working in Desktop app go to properties of log4net.config and select "Copy If Newer".



No comments:

Post a Comment