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

  <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"/>
    <layout type="log4net.Layout.PatternLayout">
      <conversionPattern value="%-5p %-25d thr:%-5t %9rms %c{1},%M: %m%n"/>
    <appender-ref ref="RollingLogFileAppender" />

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

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

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

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)