Implementing Log4Net

Log4net is an open source library that allows .NET applications to log output to a different of sources e.g., Console, SMTP, Files, IIS server. In this article, I am writing an overview of how library works and implementation of different logging options.

To get started first you need to download library, you can add library from Nuget, Just go to manage Nuget and search for log4net and install it.
Once you done with installation, then you need to do configuration for log4net. The standard way to set up a log4net logger is to utilize either the app.config file in a desktop application or the web.config file in web application. These sections will tell log4net how to configure itself. For logging information we also need Appender, It is basically a destination that the logging information will go to. In this article, I have given an example of FileAppender. Appenders can be used to log data to databases, email, net broadcasts etc. You can have as many appenders configured for use as you want.

In given example I have an appender which will create log file in ” ~\ErrorLogs\” folder, and new file created daily and named as, 'ErrorLog_'dd.MM.yyyy'.log'.


Example:-
1. Add log4Net configuration to Web.config file:

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

2. Add apender detail:-


<log4net debug="false">

  <appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender">
    <file value="ErrorLogs\" />
    <datePattern value="'ErrorLog_'dd.MM.yyyy'.log'" />
    <appendToFile value="true" />
    <rollingStyle value="Date" />
    <maxSizeRollBackups value="10" />
    <staticLogFileName value="false" />
    <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
    <layout type="log4net.Layout.PatternLayout">
      <param name="ConversionPattern" value="%n%n %-5p %m%n" />
    </layout>
  </appender>
  <root>
    <level value="All" />
    <appender-ref ref="LogFileAppender" />
  </root>
</log4net>

 3. Add log4net detail as below in assembly info file,

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

4. You are done with configuration, now error can be logged as follows,

Note:- Here I have created MVC application and overriding OnException filter and to log errors.

    //Create Log4net object
    private ILog _objLog4Net = null;

    /// <summary>
    /// Global Excception handling
    /// Created By: Mangalsing Ghunawat
    /// Created On: 04/04/2017
    /// </summary>
    /// <param name="filterContext"></param>
    protected override void OnException(ExceptionContext filterContext)
    {
        Exception ex = filterContext.Exception;

        //ERROR Date:- 2017-04-04 17:11:12,819 || ERROR - Attempted to divide by zero.|| User:- Mangal || Role: CMSUser || Environment:- Dev || Loan#:- Pick From URL
        string ErrorMessage = string.Concat(" - ", ex.Message, " || Date:- ", System.DateTime.Now, " || User:- ", Userinfo.FullName, " || Role:- ", Userinfo.UserId, " || Environment:- ", WebConfigurationManager.AppSettings["Environment"], " || Loan#:- ", LoanNumber);

        _objLog4Net = LogManager.GetLogger(filterContext.RouteData.Values["controller"].ToString());
        _objLog4Net.Error(ErrorMessage, ex);

        filterContext.ExceptionHandled = true;

        var Result = this.View("Error", new HandleErrorInfo(ex,
        filterContext.RouteData.Values["controller"].ToString(),
        filterContext.RouteData.Values["action"].ToString()));

        filterContext.Result = Result;
    }



As you can see, for logging, First we need to call GetLogger method to create/retrieve logger, Then call Error method to log error.

Log4net provides a simple mechanism for logging information, logs information via one or more loggers. The level of logging on a particular logger can be specified in configuration, following levels are defined in order of increasing priority: ALL, DEBUG, INFO, WARN, ERROR, FATAL, OFF


Thanks.


Comments