Joydip Kanjilal
Contributor

How to work with log4net in C#

how-to
Sep 16, 20165 mins
C#Microsoft .NETSoftware Development

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

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.

Installing log4net 

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 “” after the element in your app.config file. Next, inside the “” 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:ProjectsPersonalIDGIDG.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 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 available, 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.

Joydip Kanjilal
Contributor

Joydip Kanjilal is a Microsoft Most Valuable Professional (MVP) in ASP.NET, as well as a speaker and the author of several books and articles. He received the prestigious MVP award for 2007, 2008, 2009, 2010, 2011, and 2012.

He has more than 20 years of experience in IT, with more than 16 years in Microsoft .Net and related technologies. He has been selected as MSDN Featured Developer of the Fortnight (MSDN) and as Community Credit Winner several times.

He is the author of eight books and more than 500 articles. Many of his articles have been featured at Microsoft’s Official Site on ASP.Net.

He was a speaker at the Spark IT 2010 event and at the Dr. Dobb’s Conference 2014 in Bangalore. He has also worked as a judge for the Jolt Awards at Dr. Dobb's Journal. He is a regular speaker at the SSWUG Virtual Conference, which is held twice each year.

More from this author