How to work with log4net in C#

Log4net is an easy to use, reliable, fast, popular, extensible and open source library for logging data to various configured log targets

log4net

log4net

When working on applications, you may often want to log application data that may include, the sequence of events in your application, user actions or even errors when they occur. There are many logging frameworks that you can use, but log4net is by far one of the most popular logging frameworks for use with applications built or developed in .Net. It is an open source library (a port of the popular log4j open source library for Java) that can be used to log application data to different log targets in .Net.

Getting started

The easiest and quickest way to get started using log4net is by installing it through the NuGet Package Manager. Assuming that you have created a console application project in Visual Studio, you can install log4net via NuGet Manager, by following these steps.

  1. In the "Solution Explorer Window," select and right click on your project
  2. Click "Manage NuGet Packages..."
  3. Click "Online" and then type log4net in the search box
  4. Select the log4net package you would like to install
  5. Click "Install" to start the installation process

As of this writing, the latest stable release of log4net is 2.0.5. Once log4net has been installed via the NuGet Package Manager, you would observe the log4net assembly added as a reference to your project.

Configuring log4net

Now that the log4net package has been installed successfully, add the following line to the AssemblyInfo.cs file in the Properties folder of your project. If this is not specified, the configuration settings would not be considered.

[assembly: log4net.Config.XmlConfigurator(ConfigFile = "Log4Net.config", Watch = true)]

Alternatively, you can also mention the same in the app.config or the web.config file.

[assembly: log4net.Config.XmlConfigurator(Watch = true)]

If your log4net configuration metadata resides in some other file (i.e., other than web.config or app.config files), you can specify the following instead.

[assembly: log4net.Config.XmlConfigurator(ConfigFile = "log4net.config", Watch = true)]

The next step is to specify the necessary configuration details for log4net in the app.config or the web.config file in your application. Assuming that you are using a console application project, add a configuration section named "log4net" in the app.config file as shown below.

<configSections>

   <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />

</configSections>

Now, add the section "<log4net></log4net>" after the <configSections/> element in your app.config file. Next, inside the "<log4net></log4net>" section, place the configuration details as shown in the code snippet given below.

<log4net>

   <appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender">

     <param name="File" value="C:\\Projects\\Personal\\IDG\\IDG.log"/>

     <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />

     <appendToFile value="true" />

     <rollingStyle value="Size" />

     <maxSizeRollBackups value="10" />

     <maximumFileSize value="1MB" />

     <staticLogFileName value="true" />

     <layout type="log4net.Layout.PatternLayout">

       <conversionPattern value="%date [%thread] %level %logger - %message%newline" />

     </layout>

   </appender>

   <root>

     <level value="ALL" />

     <appender-ref ref="LogFileAppender" />

   </root>

</log4net>

That’s all you need to do to configure log4net. Let’s now explore how we can use it in our code. The <appender /> element is used to specify the name and type of the logger to be used. In this example we are using the rolling file appender. However, there are many other types of appenders availabile, i.e., AdoNetAppender, AspNetTraceAppender, ConsoleAppender, etc. Here is the full list and how to configure other appenders.

Using log4net

In your class, create a reference to ILog by making a call to the GetLogger static method of the LogManager class as shown in the code snippet given below.

private static readonly log4net.ILog log =

log4net.LogManager.GetLogger

(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

You can now use the instance named log to log data to the configured targets. The following code snippet illustrates how you can now take advantage of the log instance to log data.

log.Debug("This is a Debug message");

log.Info("This is a Info message");

log.Warn("This is a Warning message");

log.Error("This is an Error message");

log.Fatal("This is a Fatal message");

Here’s a complete code listing that shows how you can log your exception message in a text file using log4net.

class Program

   {

       static readonly log4net.ILog log =

       log4net.LogManager.GetLogger

(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

       static void Main(string[] args)

       {

           try

           {

               throw new Exception("This is test message...");

           }

           catch(Exception ex)

           {

               log.Error(ex.Message);

           }          

           Console.Read();

       }

   }

After you execute the above program, a text file named IDG.log will be created and the exception message specified with be logged along with the timestamp. Note that you can also use log4net programmatically, i.e., configure log4net programmatically sans the need of the configuration we discussed earlier.

This article is published as part of the IDG Contributor Network. Want to Join?

To comment on this article and other InfoWorld content, visit InfoWorld's LinkedIn page, Facebook page and Twitter stream.
From CIO: 8 Free Online Courses to Grow Your Tech Skills
Notice to our Readers
We're now using social media to take your comments and feedback. Learn more about this here.