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

A Brief Introduction to the log4net logging library, using C#

, 10 Sep 2004
Rate this:
Please Sign up or sign in to vote.
An article describing the basic use of the log4net library.

What is log4net

Log4net is an open source library that allows .NET applications to log output to a variety of sources (e.g., The console, SMTP or files). Log4net is a port of the popular log4J library used in Java. Full details of log4net can be found at its project homepage.

In this article, I will give an overview of how the library works and examples of a few of the different logging options.

Downloading the library

The log4net library can be downloaded from the project homepage. The latest distribution comes with versions of log4net for MONO, .NET 1.0 and 1.1, and .NET Compact Framework.

What does log4net provide?

Log4net provides a simple mechanism for logging information to a variety of sources. Information is logged via one or more loggers. These loggers provide 5 levels of logging:

  1. Debug
  2. Information
  3. Warnings
  4. Error
  5. Fatal

Hopefully (!!) the amount of logging performed by each level will decrease going down this list (we want more debug information than fatal errors!). The level of logging on a particular logger can be specified, hence during development, all 5 levels of logging can be output to aid development. When your application is deployed, you may decide to only output level 5 – Fatal errors to your log files. It's up to you and it's all easily configurable.

So, where does the logging information go? Well, logging information goes to what is called an Appender. An appender is basically a destination that the logging information will go to. In this article, I will give examples of the ConsoleAppender and the FileAppender. Many other appenders exist to allow data to be logged to databases, email, net broadcasts etc. You are not limited to only using one appender, you can have as many appenders configured for use as you want. Appender configuration is performed outside of code in XML files, so as we shall see later, it is a simple matter to change your logging configuration.

OK, so we know that we can use a logger to output data to a number of appenders, but what format will the information be logged as? Well, log4net has a number of layouts that can be used for each appender. These layouts specify whether the logs are produced as simple textual data or as XML files, or whether they have timestamps on them etc.

Let's get logging

OK, I'm sure you've read enough about logging now, and want to see some code and see how it all works. Well, here goes. Our first (incredibly simple) example program (LogTest.exe) is shown below:

using log4net;
using log4net.Config;

public class LogTest
    private static readonly ILog logger = 
    static void Main(string[] args)
        logger.Debug("Here is a debug log.");
        logger.Info("... and an Info log.");
        logger.Warn("... and a warning.");
        logger.Error("... and an error.");
        logger.Fatal("... and a fatal error.");

You can see that there are a few interesting lines within this small application. The first of these is where we create a Logger.

private static readonly ILog logger = 

This creates a logger for the class LogTest. You don't have to use a different logger for each class you have, you can use different loggers for different sections or packages within your code. The class of the logger is output to the log so you know where any logged information has come from.

The next interesting line is:


This method initializes the log4net system to use a simple Console appender. Using this allows us to quickly see how log4net works without having to set up different appenders. Don't worry however, setting up appenders isn't difficult and we'll look at that in a minute.

Finally, if you run the application, you can see the different levels of logging output that are performed - in this case, to the console:

0 [2436] DEBUG LogTest  - Here is a debug log.
31 [2436] INFO LogTest  - ... and an Info log.
31 [2436] WARN LogTest  - ... and a warning.
31 [2436] ERROR LogTest  - ... and an error.
31 [2436] FATAL LogTest  - ... and a fatal error.

Specifying the Appender

Let's now change the test application so that it loads the log4net configuration information from a “.config” file. This is done by removing the BasicConfigurator and using a DOMConfigurator as is shown in the sample application LogTest2.

using log4net;
using log4net.Config;

public class LogTest2
    private static readonly ILog logger = 
    static LogTest2()

    static void Main(string[] args)
        logger.Debug("Here is a debug log.");
        logger.Info("... and an Info log.");
        logger.Warn("... and a warning.");
        logger.Error("... and an error.");
        logger.Fatal("... and a fatal error.");

Now that we are using a DOMConfigurator, we need to specify our appenders and layouts. This is done in the application's .config file, “LogTest2.exe.config”.

<?xml version="1.0" encoding="utf-8" ?>
        <section name="log4net" 
           type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
        <appender name="LogFileAppender" type="log4net.Appender.FileAppender">
            <param name="File" value="LogTest2.txt" />
            <param name="AppendToFile" value="true" />
            <layout type="log4net.Layout.PatternLayout">
                <param name="Header" value="[Header]\r\n" />
                <param name="Footer" value="[Footer]\r\n" />
                <param name="ConversionPattern" value="%d [%t] %-5p %c %m%n" />
        <appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender" >
            <layout type="log4net.Layout.PatternLayout">
                <param name="Header" value="[Header]\r\n" />
                <param name="Footer" value="[Footer]\r\n" />
                <param name="ConversionPattern" value="%d [%t] %-5p %c %m%n" />

            <level value="INFO" />
            <appender-ref ref="LogFileAppender" />
            <appender-ref ref="ConsoleAppender" />

Within this XML file, you can see that there are two appenders specified, LogFileAppender and ConsoleAppender. We also have a root appender. This specifies what appenders we are using and also what level of output we want to see in our logs – in this case, everything from INFO onwards (i.e., everything except DEBUG). The LogFileAppender specifies which file to use and whether to append onto the end of an existing file or not. Both appenders use a common layout that specifies what information is output to the logs. We can see that the date (%d), time (%t), logging level (%p), the name of the logger (%c) and the message (%m) are output.

If you now run application LogTest2, the following output is shown on the console:

2004-09-10 12:53:48,062 [1216] INFO  LogTest2  - ... and an Info log.
2004-09-10 12:53:48,078 [1216] WARN  LogTest2 - ... and a warning.
2004-09-10 12:53:48,078 [1216] ERROR LogTest2 - ... and an error.
2004-09-10 12:53:48,078 [1216] FATAL LogTest2 - ... and a fatal error.

If you have a look at the file “LogTest2.txt”, you will see that it contains the same information.

Well, that's a brief overview of what log4net can do, and we've only really scratched the surface here. Log4net provides many other features and I'd recommend grabbing hold of a copy to try them out.


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


About the Author

David Salter
Web Developer
United Kingdom United Kingdom
No Biography provided

Comments and Discussions

QuestionReally great article David Salter Pinmembersacratesj29-Oct-14 3:55 
QuestionLicense Model PinmemberMember 40483933-Sep-14 21:12 
QuestionMy vote of 5 Pinmembertuanv2t18-Aug-14 1:47 
QuestionHow to log stacktrace of an exception? PinprofessionalPrasanna Krishnaswamy17-Jul-14 5:23 
General5 stars PinmemberPaul Sincai30-Jun-14 23:30 
GeneralMy vote of 3 PinmemberMember 1072483715-Apr-14 6:10 
QuestionLog4net Intro [modified] PinmemberGazYad23-Nov-13 6:20 
GeneralMy vote of 5 PinmemberMazen el Senih11-May-13 8:15 
GeneralMy vote of 3 PinmemberEhsan yazdani rad7-May-13 1:40 
GeneralMy vote of 4 PinmemberSheila Deskins4-Jan-13 9:13 
QuestionMultiple Instances of same application with different log files Pinmemberhimanshub197823-Aug-12 19:00 
QuestionSend email for only Error level provider in log4net PinmemberPankajSaha15-Feb-12 0:39 
QuestionIs there a way to specify different log destination? PinmemberMember 31191311-Jun-11 12:50 
GeneralMy vote of 4 PinmemberPravin Patil, Mumbai24-Jan-11 5:25 
GeneralGood reference article PinmemberDonsw24-Oct-10 11:26 
GeneralVery helpful Pinmembernuprin_X19-Mar-10 15:28 
GeneralAnother good link for setting and implement log4net PinmemberMD.Tanvir Anowar15-Nov-09 17:15 
GeneralNice Pinmemberguzufeng25-Sep-09 6:01 
Questionlog file name as current Date-Time PinmemberAniket Salunkhe12-May-09 4:17 
AnswerRe: log file name as current Date-Time PinmemberChetan Ranpariya29-Apr-10 20:37 
GeneralThis was very helpful Pinmemberramone.hamilton25-Mar-09 21:42 
Generalnice starting point PinmemberRadim Köhler6-Oct-08 22:25 
QuestionHow to configure a config file to log to multiple files PinmemberGambLL28-Jul-08 10:07 
AnswerRe: How to configure a config file to log to multiple files PinmemberRamkumar Vasudevan5-May-09 11:43 
QuestionHow customize Header/Footer? Pinmemberjason_X21-Jul-08 4:25 
Generalget File value Pinmembershinyhui14-Jan-08 20:40 
QuestionHelp about “LogTest2.txt” Pinmemberamirpalang27-Oct-07 2:37 
GeneralJust a hint for version 1.2.10 of log4net PinmemberM.Vo.20-Sep-07 3:57 
GeneralHello to All Codeproject .com User PinmemberKuldeep singh sethi29-Nov-06 6:23 
QuestionUrgent Help:How to config log4net1.2.9 in Test Project created in VSTS 2005 Beta2? Pinmemberautumn_it7-Feb-06 21:10 
Mad | :mad: I config log4net for a Test Project(unit test) created for my project in VSTS 2005 Beta2. It compiles successfully but no log file generated with log message. It seems that the Test Project doesn't read the manualy added App.config file. But I test the same configuration and same code in a common project of output type ="Console Application" to write log message to a txt file. It runs well and the txt file is generated with correct debug message or error message.The configuration is very simple with a App.config file and
[assembly: log4net.Config.XmlConfigurator(Watch = true)]
in AssemblyInfo.cs.The relative code is like:
private static readonly ILog logger = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
public void TestInsert()
{logger.Debug("Test insert begins!");}
Do you know what should I do to write log of a Test Project to a txt file, besides the .trx test result file?

Generalsomething Not Working PinmemberAustinn2-Jan-06 22:13 
GeneralRe: something Not Working Pinmemberwald.by31-Jul-08 2:55 
GeneralDynamically configure the config settings. Pinmembervikramlagu18-Nov-05 2:10 
GeneralHelp! Pinmemberal_todd17-May-05 9:01 
GeneralRe: Help! Pinmemberal_todd18-May-05 0:30 
GeneralRe: Help! PinsussAnonymous29-Jun-05 22:19 
GeneralRe: Help! Pinmemberal_todd30-Jun-05 0:16 
GeneralRe: Help! - about your app.config Pinmemberjwhurst18-Jul-05 5:58 
QuestionHow to provide more debug levels PinmemberBoniolopez25-Mar-05 5:02 

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 | Terms of Use | Mobile
Web02 | 2.8.150326.1 | Last Updated 10 Sep 2004
Article Copyright 2004 by David Salter
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid