Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

log4Net logging framework

0.00/5 (No votes)
12 Jul 2012 1  
This article will explain how to create a general log4net logging framework which can be used by various types of applications of Microsoft NET Framework

Introduction   

There are many articles and examples available in the internet regarding log4net. This article is focused on a scenario where you develop an enterprise application which comprises of various types of NET applications (Console, WinForm, Web, WCF, WPF, Windows Service, etc.) and want to have a single logging framework using log4net rather than configure log4net in each application which results the app/web.config files having duplicated entries. 

How this structured

Here is the solution explorer view from the attached source code. 

Solution Explorer

All the projects except Log4NetLibrary is not important as they are there just to demonstrate how the logging framework is used in different types of NET applications.Let us dig deeper into what is the big deal we have in Log4NetLibrary . 

  1. It is a class library  
  2. It has reference to the log4net.dll v1.2.11.0 which is the latest as of writing this article.However, you can check the latest version of the log4net.  
  3. It has an interface ILogService which simply helps implementing multiple types of logging.  
  4. It has a class FileLogService which implements ILogService and writing the messages to a text file.  
  5. It has a log4net.config file with the RollingFileAppender configuration details(with the size of 5 MB and maximum of 5 archive). There are, however, different types of configuration can be done in log4net, please check here for more options. 

Note: you need to change the property of log4net.config file to Copy Always as below, else the logging will not work

copy always

This class library wraps the log4net and expose the public class FileLogService with which the clients will make a call to write something to log file. This project stands very flexible in the way it has been written. For example, you can write your own class implementing the interface and write to any other medium, say database, rather than to a text file. 

Using the code

The interface ILogService wraps all the log4net methods

public interface ILogService
{
    void Fatal(string message);
    void Error(string message);
    void Warn(string message);
    void Info(string message);
    void Debug(string message);
}

The class FileLogService implementing the interface. It configures the log4net in the static constructor so that it the code will not execute for each call by the client.

static FileLogService()
{
    // Gets directory path of the calling application
    // RelativeSearchPath is null if the executing assembly i.e. calling assembly is a
    // stand alone exe file (Console, WinForm, etc). 
    // RelativeSearchPath is not null if the calling assembly is a web hosted application i.e. a web site
    var log4NetConfigDirectory = AppDomain.CurrentDomain.RelativeSearchPath ?? AppDomain.CurrentDomain.BaseDirectory;
    var log4NetConfigFilePath = Path.Combine(log4NetConfigDirectory, "log4net.config");
    log4net.Config.XmlConfigurator.ConfigureAndWatch(new FileInfo(log4NetConfigFilePath));
}

Note: There is an other way of doing this configuration in assembly wide by editing the AssemblyInfo.cs file like below:

[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
//log4net configuration
[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]

But doing this has resulted a build error like below, so I have chosen the first version (configuring at class level). Use this approach if this works for you.  

configuration build error

...and the constructor accepts a Type parameter. So a client class must supply its name before calling the methods to write log information. In this way we can see what class is writing the log messages.

public FileLogService(Type logClass)
{
    _logger = LogManager.GetLogger(logClass);
}
public void Info(string message)
{
    if (_logger.IsInfoEnabled)
        _logger.Info(message);
}
//other methods...

The client calling like

public partial class Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        ILogService logService = new FileLogService(typeof(Default));
        logService.Info("Just an information from web app");
    }
}

Using the log4net library

Ok, so the library is ready and we can test this with various types of applications. In this example, I have created WPF, Console, Win Form, ASP.NET,and two class libraries in order to test the log message is written correctly.

You can test this by running the attached source code. In VS 2010, you can set multiple projects to run, so when hitting F5 you see all is running.

Setting multiple startup projects: 

multiple startup

And they run: 

on run

Finally, the log file says: 

log file

Points of Interest

In this article, I am not giving anything new which you don't know before, but something I feel happy helping you achieving you an extendable logging framework. I have used a log4net version for NET Framework 4.0, but this does not mean that this will work only on Net Framework 4.0. For other versions of Net Framework, you can use the previous version of log4net. 

Other useful links

log4net Tutorial

http://www.mikebevers.be/blog/2010/09/logging-framework-with-log4net/

History

  1. Initial version on 9 May 2012

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here