Log4net Initialization/Configuration alternatives

In a previous post where I talked about using log4net I used one of the alternative ways to initialize and configure the logging services.

This post will summarize these alternatives.

 

1. Programmatic initialization

The programmatic initialization should be done somewhere in your code.

This was the type of initialization used on the first post and its code is something like this.

using log4net;

using log4net.Config;

public class MyApp
{
    private static readonly ILog log = LogManager.GetLogger(typeof(MyApp));

    static void Main(string[] args)
    {
        // BasicConfigurator replaced with XmlConfigurator.
        XmlConfigurator.Configure(new System.IO.FileInfo(args[0]));

            log.Info("Entering application.");

    }

}

2. Assembly attribute initialization

The assembly attribute initialization does not imply the inclusion of any code in your application. Instead, you just have to place an assembly level attribute in some file of your assembly. This way your code could be:

using log4net;

[assembly: log4net.Config.XmlConfigurator()]

public class MyApp
{
    private static readonly ILog log = LogManager.GetLogger(typeof(MyApp));

    static void Main(string[] args)
    {
        log.Info("Entering application.");
    }
}

 

The assembly level attribute by itself does not mean a instruction to initialize the logging framework. Instead, the logging framework is initialized by the first call that is made to log4net (in the example the log.Info) initialized. This means that when using assembly attributes you should make a logging call as soon as possible and before calling any other external assembly.

 

Finally, if you are using logger objects defined per-class, a simple way to define a logger object that enables it to be copy-pasted in a very simple way is to do:

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

 

This instruction uses reflection for determining the class type name that will be used in the logging messages.

For more information please refer to the log4net homepage.