log4net configuration in .NET 3.5

Step 1 Add Reference

Right click on the “References” folder and choose add reference. Browse to the location of log4net and add it to the project.

Step 2 Add Config Section Reference

In web.config, add a reference to the log4net config section handler. This will look like:

<?xml version="1.0"?>
<configuration>
 <configSections>
  <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net"/>
 <!-- other sections/sectionGroups -->
 </configSections>
</configuration>

Step 3 Add the log4net configuration Section

All that is left is to add the actual configuration. There are an unlimited number of ways this can be done, with numerous different logs and log types. An example configuration follows. This configuration creates a log for NHibernate with a max size of 8MB, a rolling file (max size 3MB), and a a console log. Anything logged to the logger named NHibernate.SQL will record only if they are ERROR level or higher. Anything logged without specifying a logger name is logged to root, and only goes to the console and rolling file.

<log4net>
  <appender name="NHibernateFileLog" type="log4net.Appender.RollingFileAppender,log4net">
   <file value="logs/nhibernate.txt"/>
   <appendToFile value="true"/>
   <rollingStyle value="Size"/>
   <maxSizeRollBackups value="0"/>
   <maximumFileSize value="8MB"/>
   <staticLogFileName value="true"/>
   <layout type="log4net.Layout.PatternLayout,log4net">
    <conversionPattern value="%d [%t] %-5p %c - %m%n"/>
   </layout>
  </appender>
  <appender name="console" type="log4net.Appender.ConsoleAppender, log4net">
   <layout type="log4net.Layout.PatternLayout,log4net">
    <param name="ConversionPattern" value="%d{ABSOLUTE} %-5p %c{1}:%L - %m%n"/>
   </layout>
  </appender>
    <!-- log4net uses 5 levels, namely DEBUG, INFO, WARN, ERROR and FATAL. -->
  <appender name="rollingFile" type="log4net.Appender.RollingFileAppender,log4net">
   <param name="File" value="logs/RollingLog.txt"/>
   <param name="AppendToFile" value="false"/>
   <param name="RollingStyle" value="Date"/>
   <param name="DatePattern" value="yyyy.MM.dd"/>
   <param name="StaticLogFileName" value="true"/>
   <maximumFileSize value="3MB"/>
   <maxSizeRollBackups value="0"/>
   <staticLogFileName value="true"/>
   <layout type="log4net.Layout.PatternLayout,log4net">
    <param name="ConversionPattern" value="%d{HH:mm:ss.fff} [%t] %-5p %c - %m%n"/>
   </layout>
  </appender>
  <logger name="NHibernate.SQL" additivity="false">
   <level value="ERROR"/>
   <appender-ref ref="NHibernateFileLog"/>
   <appender-ref ref="console"/>
   <appender-ref ref="rollingFile"/>
  </logger>
  <root>
   <level value="ERROR"/>
   <appender-ref ref="console"/>
      <appender-ref ref="rollingFile"/>
   <!--Uncomment the following appender for verbose output (degrades performance)-->
   <!--<appender-ref ref="rollingFile"/>-->
  </root>
 </log4net>

Step 4

Now, all that’s left is to call log4net’s configure method before any other (read: **error prone**) code is called.

For example, in an ASP.NET Web application, you could add this to Global.asax:

public class GlobalAsax : HttpApplication
{
    void Application_Start(object sender, EventArgs e)
    {
        log4net.Config.XmlConfigurator.Configure();
    }
}

Other logging options include database, mail, net, access.

For more information and examples on log4net, visit http://logging.apache.org/log4net/release/config-examples.html

An example Logger implementation in C#:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using log4net;
using log4net.Config;
namespace ETeacherWeb.Common
{
    /// <summary>
    /// Logger class for log4net programmatic logging
    /// </summary>
    public static class Logger
    {
        /// <summary>
        /// Severity/Level of the log entry
        /// </summary>
        public enum LogLevel
        {
            DEBUG = 1,
            ERROR,
            FATAL,
            INFO,
            WARN
        }
        #region Members
        private static readonly ILog logger = LogManager.GetLogger(typeof(Logger));
        #endregion
        #region Constructors
        static Logger()
        {
            XmlConfigurator.Configure();
        }
        #endregion
        #region Methods
        /// <summary>
        /// Write a string to the log with a specified level of severity
        /// </summary>
        /// <param name="logLevel">The severity of the log entry</param>
        /// <param name="log">The log entry</param>
        public static void WriteLog(LogLevel logLevel, String log)
        {
            if (logLevel.Equals(LogLevel.DEBUG))
            {
                logger.Debug(log);
            }
            else if (logLevel.Equals(LogLevel.ERROR))
            {
                logger.Error(log);
            }
            else if (logLevel.Equals(LogLevel.FATAL))
            {
                logger.Fatal(log);
            }
            else if (logLevel.Equals(LogLevel.INFO))
            {
                logger.Info(log);
            }
            else if (logLevel.Equals(LogLevel.WARN))
            {
                logger.Warn(log);
            }
        }
        #endregion
    }
}
 

To use the above code, you would call

Logger.WriteLog(LogLevel.DEBUG, "The expected logic failed validation");

Related Articles