Using Log4Net with C# Applications

Step 1: Download Log4Net from http://logging.apache.org/log4net/download.html.

Step 2: Copy the \bin\net\2.0\release\log4net.dll to your project.

Step 3: Add a reference to the dll in your project.

Step 4: Add the following line to your assemblyinfo.cs

[assembly: log4net.Config.XmlConfigurator(ConfigFile="Log4Net.config", Watch=true)]

Step 5: Create new config file in your project and name it Log4Net.config. Put the following configuration in it.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />
  </configSections>
 
  <log4net debug="true">
    <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
      <file value="/applicationLog.txt" />
      <appendToFile value="true" />
      <rollingStyle value="Size" />
      <maxSizeRollBackups value="10" />
      <maximumFileSize value="10MB" />
      <staticLogFileName value="true" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%-5p %d %5rms %-22.22c{1} %-18.18M - %m%n" />
      </layout>
    </appender>
 
    <root>
      <level value="DEBUG" />
      <appender-ref ref="RollingLogFileAppender" />
    </root>
  </log4net>
</configuration>

Step 6: Use the name space in your application as

using log4net;

Step 7: Create a logger instance by using

private static log4net.ILog log = log4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

Step 8: Harness the power of log4net by using its inbuilt methods such as

catch (Exception ex)
            {
                log.Fatal(ex.Message);
            }
Share Article/Example:
  • Facebook
  • Twitter
  • del.icio.us
  • Digg
  • DotNetKicks
  • DZone