Implement Log4net In ASP.NET MVC Application
Tags: aspnet, l
Published: 2023-08-23 10:36:21

## **Definition:**
Log4Net is a framework for implementing logging mechanisms. It is an open-source framework.

Log4net provides a simple mechanism for logging information to a variety of sources. Information is logged via one or more loggers. These loggers are provided at the below levels of logging:

Debug
Information
Warnings
Error
Fatal

Now let’s begin with implementation.

## **1.Add log4net Package:**
For Implementation At First, you need to install log4net from NuGet Package Manager to your ASP.NET MVC project as per the below screen.
![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/yibts5rmdemrr7r8834l.JPG)

## **2.Configure log4net in Global.asax:**
Once installation Complete, you need to add the below code in Application_Start() Method of Global.asax

=>`log4net.Config.XmlConfigurator.Configure();`

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/a0agfokuy16yxdl2ru54.JPG)

## **3.Configure Web Config File** 
Implementing a specific file for accessing throughout the application. Now, open Web.Config File and Add the following details.



![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/99k195psaberdr8vvpes.JPG)
`<configuration>`

 `<configSections>
    <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" />
  </configSections>`
 `<log4net>
    <appender name="RollingFile" type="log4net.Appender.RollingFileAppender">
      <file value="C:\Temp\nSightsLog.log" />
      <appendToFile value="true" />
      <maximumFileSize value="500KB" />
      <maxSizeRollBackups value="2" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date %level %logger - %message%newline" />
      </layout>
    </appender>
    <root>
      <level value="All" />
      <appender-ref ref="RollingFile" />
    </root>
  </log4net>`

`</configuration>`

## **4.Log Class Configuration**

Add a class Log.cs in the Utilities folder. 

Now, in the constructor of this class, instantiate logs for monitoring and debugger loggers.
`private Log()
{
    monitoringLogger = LogManager.GetLogger("MonitoringLogger");
    debugLogger = LogManager.GetLogger("DebugLogger");
}`
Here, you need to create Debug(), Error(), Info(), Warn(), and Fatal() methods, which will call respective methods from Log4 net.

Below is a sample.

`public class Log
{
    private static readonly Log _instance = new Log();
    protected ILog monitoringLogger;
    protected static ILog debugLogger;

    private Log()
    {
        monitoringLogger = LogManager.GetLogger("MonitoringLogger");
        debugLogger = LogManager.GetLogger("DebugLogger");
    }

    /// <summary>
    /// Used to log Debug messages in an explicit Debug Logger
    /// </summary>
    /// <param name="message">The object message to log</param>
    public static void Debug(string message)
    {
        debugLogger.Debug(message);
    }
    /// <summary>
    ///
    /// </summary>
    /// <param name="message">The object message to log</param>
    /// <param name="exception">The exception to log, including its stack trace </param>
    public static void Debug(string message, System.Exception exception)
    {
        debugLogger.Debug(message, exception);
    }
    /// <summary>
    ///
    /// </summary>
    /// <param name="message">The object message to log</param>
    public static void Info(string message)
    {
        _instance.monitoringLogger.Info(message);
    }
    /// <summary>
    ///
    /// </summary>
    /// <param name="message">The object message to log</param>
    /// <param name="exception">The exception to log, including its stack trace </param>
    public static void Info(string message, System.Exception exception)
    {
        _instance.monitoringLogger.Info(message, exception);
    }

    /// <summary>
    ///
    /// </summary>
    /// <param name="message">The object message to log</param>
    public static void Warn(string message)
    {
        _instance.monitoringLogger.Warn(message);
    }

    /// <summary>
    ///
    /// </summary>
    /// <param name="message">The object message to log</param>
    /// <param name="exception">The exception to log, including its stack trace </param>
    public static void Warn(string message, System.Exception exception)
    {
        _instance.monitoringLogger.Warn(message, exception);
    }

    /// <summary>
    ///
    /// </summary>
    /// <param name="message">The object message to log</param>
    public static void Error(string message)
    {
        _instance.monitoringLogger.Error(message);
    }

    /// <summary>
    ///
    /// </summary>
    /// <param name="message">The object message to log</param>
    /// <param name="exception">The exception to log, including its stack trace </param>
    public static void Error(string message, System.Exception exception)
    {
        _instance.monitoringLogger.Error(message, exception);
    }
    /// <summary>
    ///
    /// </summary>
    /// <param name="message">The object message to log</param>
    public static void Fatal(string message)
    {
        _instance.monitoringLogger.Fatal(message);
    }

    /// <summary>
    ///
    /// </summary>
    /// <param name="message">The object message to log</param>
    /// <param name="exception">The exception to log, including its stack trace </param>
    public static void Fatal(string message, System.Exception exception)
    {
        _instance.monitoringLogger.Fatal(message, exception);
    }
}`

## **5.Action Controller:**

Now, you need to call the logger class that logs directly into your action method.
`public ActionResult Login()
{
    //This is for example , we need to remove this code later
    Log.Info("Login-page started...");

    // Boolean msg = CheckSetupType();
    return View();
}`

Finally Run The Application & A Log File Will be generated on C Drive Temp Folder 
Location: C:\Temp\AbcProjectLog.log"