Click here to Skip to main content
14,833,054 members
Articles / Programming Languages / C#
Posted 8 May 2012

Tagged as


39 bookmarked

log4Net logging framework

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


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("")]
[assembly: AssemblyFileVersion("")]
//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)
//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


  1. Initial version on 9 May 2012


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Prabu ram
Architect CGI
India India
No Biography provided

Comments and Discussions

QuestionThanks! Pin
sangram k pattanayak21-Jul-15 9:21
Membersangram 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
Memberpepe_lu7-Jan-15 5:01 
QuestionTypeInitialization Exception while using Log4NetLibraty in BAL library classes Pin
Kumar266718-Oct-14 0:28
MemberKumar266718-Oct-14 0:28 
AnswerRe: TypeInitialization Exception while using Log4NetLibraty in BAL library classes Pin
Prabu ram22-Oct-14 18:42
MemberPrabu ram22-Oct-14 18:42 
QuestionWhat about in Windows Service Application? Pin
Aneev Reddy4-May-14 23:02
MemberAneev Reddy4-May-14 23:02 
AnswerRe: What about in Windows Service Application? Pin
Prabu ram5-May-14 18:39
MemberPrabu ram5-May-14 18:39 
QuestionWhere is the log file? Pin
batuhan karaduman30-May-13 3:35
Memberbatuhan karaduman30-May-13 3:35 
AnswerRe: Where is the log file? Pin
Prabu ram20-Jul-13 20:19
MemberPrabu ram20-Jul-13 20:19 
GeneralRe: Where is the log file? Pin
SamAuYeung10-Mar-14 21:40
MemberSamAuYeung10-Mar-14 21:40 
GeneralRe: Where is the log file? Pin
SamAuYeung10-Mar-14 21:50
MemberSamAuYeung10-Mar-14 21:50 
QuestionNo levels are enabled Pin
pshirv20-May-13 9:34
Memberpshirv20-May-13 9:34 
AnswerRe: No levels are enabled Pin
Prabu ram20-Jul-13 20:29
MemberPrabu ram20-Jul-13 20:29 
QuestionCheckout ReflectInsight Pin
Ross1000015-May-13 6:50
MemberRoss1000015-May-13 6:50 
GeneralMy vote of 5 Pin
Paul Chu9-Feb-13 18:57
MemberPaul Chu9-Feb-13 18:57 
GeneralRe: My vote of 5 Pin
Prabu ram12-Feb-13 1:37
MemberPrabu ram12-Feb-13 1:37 
GeneralVery nice job ! Pin
Paul Chu9-Feb-13 18:56
MemberPaul Chu9-Feb-13 18:56 
GeneralRe: Very nice job ! Pin
Prabu ram12-Feb-13 1:38
MemberPrabu ram12-Feb-13 1:38 
GeneralMy vote of 5 Pin
Member 81676656-Dec-12 23:04
MemberMember 81676656-Dec-12 23:04 
GeneralRe: My vote of 5 Pin
Prabu ram11-Dec-12 17:24
MemberPrabu ram11-Dec-12 17:24 
GeneralMy vote of 5 Pin
amihai114-Oct-12 7:28
Memberamihai114-Oct-12 7:28 
GeneralRe: My vote of 5 Pin
Prabu ram17-Oct-12 18:52
MemberPrabu ram17-Oct-12 18:52 
Questionnice job , good implementation and explaination , thanks Pin
amihai114-Oct-12 7:24
Memberamihai114-Oct-12 7:24 
GeneralMy vote of 5 Pin
NK74-Jul-12 22:47
MemberNK74-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.