Click here to Skip to main content
Click here to Skip to main content

log4Net logging framework

, 12 Jul 2012
Rate this:
Please Sign up or sign in to vote.
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Prabu ram
Technical Lead CGI
India India
No Biography provided
Follow on   LinkedIn

Comments and Discussions

 
QuestionWhat about in Windows Service Application? PinmemberAneev Reddy4-May-14 23:02 
AnswerRe: What about in Windows Service Application? PinmemberPrabu ram5-May-14 18:39 
QuestionWhere is the log file? Pinmemberalexalexalex190730-May-13 3:35 
AnswerRe: Where is the log file? PinmemberPrabu ram20-Jul-13 20:19 
GeneralRe: Where is the log file? PinmemberSamAuYeung10-Mar-14 21:40 
GeneralRe: Where is the log file? PinmemberSamAuYeung10-Mar-14 21:50 
QuestionNo levels are enabled Pinmemberpshirv20-May-13 9:34 
AnswerRe: No levels are enabled PinmemberPrabu ram20-Jul-13 20:29 
QuestionCheckout ReflectInsight PinmemberRoss1000015-May-13 6:50 
GeneralMy vote of 5 PinmemberPaul Chu9-Feb-13 18:57 
GeneralRe: My vote of 5 PinmemberPrabu ram12-Feb-13 1:37 
GeneralVery nice job ! PinmemberPaul Chu9-Feb-13 18:56 
GeneralRe: Very nice job ! PinmemberPrabu ram12-Feb-13 1:38 
GeneralMy vote of 5 PinmemberMember 81676656-Dec-12 23:04 
GeneralRe: My vote of 5 PinmemberPrabu ram11-Dec-12 17:24 
GeneralMy vote of 5 Pinmemberamihai114-Oct-12 7:28 
GeneralRe: My vote of 5 PinmemberPrabu ram17-Oct-12 18:52 
Questionnice job , good implementation and explaination , thanks Pinmemberamihai114-Oct-12 7:24 
GeneralMy vote of 5 PinmemberNK74-Jul-12 22:47 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web04 | 2.8.140821.2 | Last Updated 12 Jul 2012
Article Copyright 2012 by Prabu ram
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid