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..


    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.

    After this you will find log4net in referenced libraries of the selected projects.


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


    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.
    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)

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

            log.Info("Exception Message");

If we run the program then it will show log message in console.

No comments :

Post a Comment