Gain Control of your .NET Logging Using log4net

have always considered logging a critical function of any production application; however, it’s often overlooked. Logging is often added to the application only after the functionality is already defined and sometimes even after the application has been completely developed.

Many frameworks implement easy and flexible logging functionality in your applications. One of the best-known frameworks for .NET is log4net. This framework is based on the popular “log4j” framework, which was originally developed for Java applications. Log4net is characterized by extremely flexible XML file configuration, a variety of log targets and output formatting options. And of course it comes with full source code.

Starting log4net
I’m not going to go through setup procedure for log4net; instead, I’ll just give you some pointers so you’ll be able to start logging quickly. For those of you just starting to use the framework, the log4net documentation is excellent.

Here are the basic steps to set up logging in your application:

  1. Create an XML configuration file for the log4net framework to use. This configuration file specifies logger sections, appenders, and the relationships between the two.
  2. Load the configuration file using the following code:
  3.    [assembly : log4net.Config.XmlConfigurator(      Watch=true)]
  4. Create a log variable that you will use to write log entries.
  5. Use the methods [logvariable].Log(), .Warn(), .Error() or other available methods to write log entries.

XML Configuration files
You can store configuration information in a separate configuration file or as a part of your project’s app.config file and is the simplest way to set up log4net logging parameters. It’s worth mentioning that anything you can set up via configuration files in log4net can be accomplished through code as well. However, XML configuration files support automatic reloading which can be extremely useful for changing the log configuration while the program is already executing, for example to temporarily enable debug output. For more information about log4net configuration see this section of the log4net documentation.

It’s worth mentioning that anything you can set up in log4net via configuration files can be accomplished through code as well.

You must define two main elements in the configuration file: loggers and appenders. Loggers specify classes/namespace hierarchies to be logged, while appenders specify the location to which log4net will log entries. Appenders are destinations that will be used for displaying or storing log entries.

Here’s a basic configuration section:

   <>     <
> <> <> <> <> <> <> <> <> <> <> <> <> <> <> <> <>

The system logs entries from the most specific to the most general; in other words, specific loggers will be used when the namespace and class name of the class to be logged are specified explicitly in the configuration. If no match is found, the system applies the root logger and its specified appender, which is the console in the preceding configuration example.

Initializing and Using Log4net
You need only two simple steps to initialize and use log4net:

  1. Add an assembly-level attribute to the executing assembly as shown below:
  2.    [assembly : log4net.Config.XmlConfigurator(Watch=true)]

    The preceding attribute causes the log4net framework to load the XML configuration from the app.config file and monitor the file for any configuration changes. You can also use the XmlConfigurator class to load and watch configuration files by calling the Configure() and ConfigureAndWatch() methods directly.

  3. Next, create a static variable that you’ll use to call log4net framework, and use the default LogManager to initialize it to the default Logger implementation
       private static readonly ILog log = LogManager.GetLogger(      System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

You should declare a static variable in each class for logging information; you should not share the variable across classes. However, by bending that rule and knowing that logger properties are initialized at the point of variable declaration, it is possible to create multiple logger instances initialized to different values.

To send a string for logging, use the Debug(), Info(), Error() or other methods available through your declared variable from the ILog interface.

You should declare a static variable in each class for logging information; you should not share the variable across classes.

Custom Appenders: Adding Destinations
One common customization is creating a custom appender that logs messages to a proprietary destination, such as an MSMQ queue, a database table, etc. Log4net makes it extremely easy to create custom appenders. A custom appender class must implement the IAppender interface. The easiest (and recommended) way is to create a class that inherits from the log4net.Appender.AppenderSkeleton class, and implement the required function void Append(LoggingEvent loggingEvent). What you do within the loggingEvent method is entirely up to you, based on the needs of your custom appender. For example, here’s a custom appender that simply shows a MessageBox:

   protected override void Append(LoggingEvent loggingEvent)   {      MessageBox.Show(RenderLoggingEvent(loggingEvent));   }

A couple of things you should remember:

  • Appenders are called in the order in which you define them in the configuration file.
  • Calls to appenders are synchronous and therefore you should optimize custom appenders for speed.

The log4net framework loads appenders using reflection because that makes it possible to reference classes that exist in both the executing assembly and in different assemblies by specifying full assembly reference in the configuration element.

Custom Loggers: Adding Message Attributes
Another more advanced customization is required to implement a custom logging interface to allow adding of additional attributes or tags to each message logged. A possible scenario is an application component that’s required to provide a CustomerId in with a logging call. This requires extending ILog interface, a custom Logger, and a custom LogManager that will create an instance of the logger. All three tasks are very straight forward.

I’ve based this example on the log4net documentation for a template (see the downloadable code for this article). Look at log4netextensions
et1.0log4net.Ext.EventIDcssrc
for the custom logger extension code.

Start by creating a public interface named ICustomLog that inherits from ILog. Add the definitions for the Debug(), Info(), Warn(), Error(), and Fatal() methods by using the following signatures

   void Debug(stringCustomerId, object message);   void Debug(stringCustomerId, object message, Exception t);

Next, using the EventIDLogImpl.cs sample file as a base, implement a CustomLogImpl class. In this class, declare a static variable called ThisDeclaringType as follows:

   private readonly static Type ThisDeclaringType =       typeof(CustomLogImpl);

Then implement the ICustomLog member methods using the following template

   public void Debug(string CustomerId, object message)   {      Debug(CustomerId, message, null);   }      public void Debug(string CustomerId, object message, Exception t)   {      if (this.IsDebugEnabled)      {         LoggingEvent loggingEvent = new             LoggingEvent(ThisDeclaringType, Logger.Repository,             Logger.Name, Level.Debug, message, t);         loggingEvent.Properties["CustomerId"] = CustomerId;         Logger.Log(loggingEvent);      }   }

Change this.IsDebugEnabled and Level.Debug to the appropriate values for the other functions.

The last class you’ll need to implement is a CustomLogManager. Because the implementation is not exactly straightforward, I recommend that you make a copy of the EventIDLogManager class from the sample directory, and then run a search-and-replace command, changing “EventID” to “Custom.” The code below illustrates the type (although not the full extent) of the required changes.

      public class EventIDLogManager      {            #region Constructor            ///          /// Private constructor to prevent object creation         ///          private EventIDLogManager() { }            #endregion         // Becomes...         public class CustomLogManager      {            #region Constructor            ///          /// Private constructor to prevent object creation         ///          private CustomLogManager() { }            #endregion      

Using a custom logger is as easy as using the original logger that comes with log4net. The only real difference is that you declare a log variable of the CustomLogManager type and use ICustomLog interfaces, for example:

   private static readonly ICustomLog log =       CustomLogManager.GetLogger(      System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

A number of logging frameworks exist on the market, some with commercial backing, and some with open source origins. Log4net is an extremely powerful logging framework that has been proven time and time again in large production environments. It is highly scalable, extensible, and it’s a logging option that makes it possible to easily implement flexible and reliable logging in all your applications.

Share the Post:
Share on facebook
Share on twitter
Share on linkedin

Overview

Recent Articles: