Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Perfect Log4Net with C#

0.00/5 (No votes)
20 Jun 2016 1  
Don't know how to store the logging message into a text file? Let's get started with Log4Net in this tutorial.

Introduction

Nowadays, most applications use logging as a way to store information about performed operations, because those data are very useful when you have to diagnose issues while running your apps. We have many ways to store the log into database, textfile, etc. Instead of using complex ways, go ahead to use an easier to use and existing open source library such as log4net. It's a common library, very powerful and the most important is very easy to use.

Should Know Before Starting

  • Application demo: Console app
  • Log4Net version: 2.0.5
  • Visual Studio: 2015

There are 5 log message levels:

  • FATAL
  • ERROR
  • WARN
  • INFO
  • DEBUG

You will also be able to find the video link here: Perfect Log4Net with C#

Integration Steps

Follows the steps to do the integration between Log4Net and C# Console application as example:

Step 1

Open your Visual Studio instance on your PC.

Step 2

Create a console project.

Step 3

Add log4net refer to your project. We have 2 ways for adding that library. The first one is download the log4net from the internet to your local device, then add the reference to DLL file. The second one is download it from Nuget. I preferred this way by the following:

  • Right clicks on your project
  • Click Manage NuGet Packages…
  • Clicks on Browse on the left hand
  • Type log4net in search box under Browse option
  • Select log4net package and click Install

Step 4

Open AssemblyInfo.cs file under Properties, then add the below line of code under the [assembly: AssemblyCulture("")] line.

// Let log4net know that it can look for configuration in the default application config file
[assembly: log4net.Config.XmlConfigurator(Watch = true)] 

Step 5

Open the App.config file, by default after creating the console app, it will contain the following code:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <startup>
    <supportedRuntime version="v4.0" 
    sku=".NETFramework,Version=v4.5.2" />
  </startup>  
</configuration>

Next, add the configuration code for log4net into this file, but don't forget to add those configurations before <startup> </startup> tag to make sure the log4net runs well. After that, it should be:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <configSections>
    <section name="log4net" 
    type="log4net.Config.Log4NetConfigurationSectionHandler,Log4net"/>
  </configSections>

  <log4net>
    <appender name="TestAppender" 
    type="log4net.Appender.RollingFileAppender" >
      <file value="E:\log\MyTestAppender.log" />
      <encoding value="utf-8" />
      <appendToFile value="true" />
      <rollingStyle value="Date" />
      <!--<rollingStyle value="Size" />
      <maxSizeRollBackups value="5" />
      <maximumFileSize value="5MB" />
      <staticLogFileName value="true" />-->
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date %level [%thread] %type.%method - %message%n" />
      </layout>
    </appender>
    <root>
      <level value="All" />
      <!-- If the following line is not included the log file 
      will not be created even if log4net is configured with this file. -->
      <appender-ref ref="TestAppender" />
    </root>
  </log4net>

  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
  </startup>
  
</configuration>

I'm going to explain a little for the above configured.

This line of code...

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

...lets the log4net know that the real configuration is stored in XML node called log4net, where we can setup the output log file, define the output layout for messages and set the roolingstyle for data file, etc.

Step 6

Open the Program.cs file, by default, it contains only the Main(string[] args) method. Go ahead to create a method called ImplementLoggingFuntion, which implements the logging feature using log4net. The full code for Program.cs is as below:

using System;
using log4net;
using System.Threading;

namespace Log4Net.CSharp
{
    class Program
    {
        //Declare an instance for log4net
        private static readonly ILog Log = 
              LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);
        static void Main(string[] args)
        {
            ImplementLoggingFuntion();
        }

        private static void ImplementLoggingFuntion()
        {
            /* We have 5 levels of log message. Let's test all.
             *  FATAL
                ERROR
                WARN
                INFO
                DEBUG
             */
            var secs = 3;
            Log.Fatal("Start log FATAL...");
            Console.WriteLine("Start log FATAL...");
            Thread.Sleep(TimeSpan.FromSeconds(secs)); // Sleep some secs

            Log.Error("Start log ERROR...");
            Console.WriteLine("Start log ERROR...");
            Thread.Sleep(TimeSpan.FromSeconds(secs)); // Sleep some secs

            Log.Warn("Start log WARN...");
            Console.WriteLine("Start log WARN...");
            Thread.Sleep(TimeSpan.FromSeconds(secs)); // Sleep some secs

            Log.Info("Start log INFO...");
            Console.WriteLine("Start log INFO...");
            Thread.Sleep(TimeSpan.FromSeconds(secs)); // Sleep some secs

            Log.Debug("Start log DEBUG...");
            Console.WriteLine("Start log DEBUG...");
            Thread.Sleep(TimeSpan.FromSeconds(secs)); // Sleep some secs

            Console.WriteLine("Press any key to close the application");
            Console.ReadKey();
        }
    }
}

Points of Interest

  • You can reuse this code for your working purposes
  • Very basic, demonstrates and easy to understand

History

  • 21-June-2016: Initial version

License

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