Click here to Skip to main content
15,867,308 members
Articles / Programming Languages / C#
Tip/Trick

log4Net logging framework

Rate me:
Please Sign up or sign in to vote.
4.94/5 (14 votes)
12 Jul 2012CPOL3 min read 114.5K   6.4K   39   23
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

C#
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.

C#
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:

C#
[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.

C#
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

C#
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)


Written By
Architect CGI
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionThanks! Pin
sangram k pattanayak21-Jul-15 9:21
sangram k pattanayak21-Jul-15 9:21 
Question¿Keeping the log file within the solution, in order to don´t change the config once is deployed? Pin
pepe_lu7-Jan-15 5:01
pepe_lu7-Jan-15 5:01 
QuestionTypeInitialization Exception while using Log4NetLibraty in BAL library classes Pin
Kumar266718-Oct-14 0:28
Kumar266718-Oct-14 0:28 
AnswerRe: TypeInitialization Exception while using Log4NetLibraty in BAL library classes Pin
Prabu ram22-Oct-14 18:42
Prabu ram22-Oct-14 18:42 
QuestionWhat about in Windows Service Application? Pin
Aneev Reddy4-May-14 23:02
Aneev Reddy4-May-14 23:02 
AnswerRe: What about in Windows Service Application? Pin
Prabu ram5-May-14 18:39
Prabu ram5-May-14 18:39 
QuestionWhere is the log file? Pin
batuhan karaduman30-May-13 3:35
batuhan karaduman30-May-13 3:35 
AnswerRe: Where is the log file? Pin
Prabu ram20-Jul-13 20:19
Prabu ram20-Jul-13 20:19 
GeneralRe: Where is the log file? Pin
SamAuYeung10-Mar-14 21:40
SamAuYeung10-Mar-14 21:40 
GeneralRe: Where is the log file? Pin
SamAuYeung10-Mar-14 21:50
SamAuYeung10-Mar-14 21:50 
QuestionNo levels are enabled Pin
pshirv20-May-13 9:34
pshirv20-May-13 9:34 
AnswerRe: No levels are enabled Pin
Prabu ram20-Jul-13 20:29
Prabu ram20-Jul-13 20:29 
QuestionCheckout ReflectInsight Pin
Ross1000015-May-13 6:50
Ross1000015-May-13 6:50 
GeneralMy vote of 5 Pin
Paul Chu9-Feb-13 18:57
Paul Chu9-Feb-13 18:57 
GeneralRe: My vote of 5 Pin
Prabu ram12-Feb-13 1:37
Prabu ram12-Feb-13 1:37 
GeneralVery nice job ! Pin
Paul Chu9-Feb-13 18:56
Paul Chu9-Feb-13 18:56 
GeneralRe: Very nice job ! Pin
Prabu ram12-Feb-13 1:38
Prabu ram12-Feb-13 1:38 
GeneralMy vote of 5 Pin
Member 81676656-Dec-12 23:04
Member 81676656-Dec-12 23:04 
GeneralRe: My vote of 5 Pin
Prabu ram11-Dec-12 17:24
Prabu ram11-Dec-12 17:24 
GeneralMy vote of 5 Pin
amihai114-Oct-12 7:28
amihai114-Oct-12 7:28 
GeneralRe: My vote of 5 Pin
Prabu ram17-Oct-12 18:52
Prabu ram17-Oct-12 18:52 
Questionnice job , good implementation and explaination , thanks Pin
amihai114-Oct-12 7:24
amihai114-Oct-12 7:24 
GeneralMy vote of 5 Pin
NK74-Jul-12 22:47
NK74-Jul-12 22:47 

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

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