Friday, October 7, 2016

How to configure log4net in .NET projects?

log4net is an open source library that help the programmer output log statements to a variety of output targets in .NET .
Here we are going setup logging using the Log4Net. Below are the necessary step to get Log4Net in the project and configure it:
  1. Right click on the solution in the “Solution Explorer” and select “Manage Nuget Packages for Solutions..

    image_thumb[9][4]_thumb[2][1]

    Now search for the log4net using the search box and you will find the log4net by Apache Software foundation. The another thing need to remember is that you have to select the projects on the right side where log4net reference is required. It should be in start up project and another projects are optional to add the reference of the log4net.

    image_thumb[10][4]_thumb[3][1]
    After this you will find log4net in referenced libraries of the selected projects.

    image_thumb13[4]_thumb[1][1]


    This can be done by running the “Install-Package” command on the “Package Manager Console” as seen in below image:

    image_thumb[13][4]_thumb[1][1]

    Alternative, you can download the binaries from Apache.Org website and reference them manually in the project where logging is required’'.
  2. Now you need to configure log4net to log the information or errors to different targets e.g Console, file, database etc. Right now we are going to configure it for the easiest way to log the information.

    Using log4net is a three stage process. First thing we need to do is configure log4net. For an example, below are simple steps to configure the BasicConfigurator.
    log4net.Config.BasicConfigurator.Configure();
    In second step, is to get Logger object using the static method GetLogger of the LogManager to log using the log4net:
    var log = log4net.LogManager.GetLogger(typeof(Program));
    After that use the logger object to log the message:

    log.Info("Exception Message");

Complete code snippet:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Log4NetConsoleCSharp
{
    class Program
    {
        static void Main(string[] args)
        {
            log4net.Config.BasicConfigurator.Configure();

            var log = log4net.LogManager.GetLogger(typeof(Program));

            log.Info("Exception Message");

            Console.ReadKey();
        }
    }
}
If we run the program then it will show log message in console.
image_thumb15[4]_thumb[1][1]