Monday, June 01, 2009

log4net – configuration via a separate file

Typically log4net is configured by inserting the log4net element into the application configuration file. Another method that can provide more flexibility is to use a separate config file used to store only log4net settings. Here is how to do that:

1. Move the log4net element from the web.config file to a separate file (I call it log4net.config). The file should begin and end with the log4net element. Here is a sample

<log4net>
  <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">
    <file value="logs//Gateway.log"/>
    <appendToFile value="true"/>
    <datePattern value="yyyyMMdd"/>
    <rollingStyle value="Date"/>
    <MaxSizeRollBackups value="180" />
    <filter type="log4net.Filter.LevelRangeFilter">
      <acceptOnMatch value="true"/>
      <levelMin value="DEBUG"/>
      <levelMax value="FATAL"/>
    </filter>
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%-5p %-25d thr:%-5t %9rms %c{1},%M: %m%n"/>
    </layout>
  </appender>
  <root>
    <appender-ref ref="RollingLogFileAppender" />
  </root>
</log4net>

2. Make sure that you have the following element in the web.config file

<configuration>
  <configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"
             requirePermission="false"/>
  </configSections>
.............

3. In the Global.asax file add the following code:

void Application_Start(object sender, EventArgs e) 
{
    System.IO.FileInfo fi = new System.IO.FileInfo(Server.MapPath("~/log4net.config"));
    if (fi != null && fi.Exists)
    {
        // Code that runs on application startup
        log4net.Config.XmlConfigurator.Configure(fi);
    }
}

4. Use the following code to instantiate Log4Net as a member variable of a class that will be performing logging:

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

5. Finally use the following code to log information:

log.Debug("Hello World");
log.Error("Hello Jupiter");

1 comment:

Anonymous said...

Very good!

Instead of doing the direct call I prefers this:

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

And its important to say that if you put your log4net configuration into a separate file, you have to make sure it is deployed to the application folder! (Properties => Copy to output directory => Copy if newer)

Greetings,
Marcus