loader
Loading...
WelCome TO My Blog
Asp.Net MVC 24 April 2018

How To Use Log4Net In MVC to Track Error with Custome Exception Filter

By dhiren

After a long time cool

What is Log4Net?

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.

 

Step 1: Add the necessary Log4Net reference

Select Tools > NuGet Package Manager.

Type in the following command:

Install-Package log4net

log4net website for NuGet can be found here:

https://www.nuget.org/packages/ log4net/

 

Step 2: Add Global.asax for loading log4net  configuration

Once installation is done, you need to add the below code in Application_Start() of  Global.asax

log4net.Config.XmlConfigurator.Configure(); 

 

Step 3: Add the following line to the AssemblyInfo.cs file:

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

 

Step 4: Add log4net in web.config file

<configSections>

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

  </configSections>

<log4net>

    <root>

      <level value="ALL"></level>

      <appender-ref ref="AdoNetAppender"></appender-ref>

    </root>

     <appender name="AdoNetAppender" type="log4net.Appender.AdoNetAppender">

      <bufferSize value="1" />

      <connectionType value="System.Data.SqlClient.SqlConnection,  

   System.Data, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />

       <connectionStringName value="DefaultConnection" />

      <commandText value="INSERT INTO dbo.Log ([Date],[Thread],[Level],[Logger],[Message],[Exception],[ActionName],[LineNumber],[Controller],[MethodName])

                          VALUES (@log_date, @thread, @log_level,@logger, @message, @exception,@action_name,@line_number,@controller,@method_name)" />

      <parameter>

        <parameterName value="@log_date" />

        <dbType value="DateTime" />

        <layout type="log4net.Layout.RawTimeStampLayout" />

      </parameter>

      <parameter>

        <parameterName value="@thread" />

        <dbType value="String" />

        <size value="255" />

        <layout type="log4net.Layout.PatternLayout">

          <conversionPattern value="%thread" />

        </layout>

      </parameter>

      <parameter>

        <parameterName value="@log_level" />

        <dbType value="String" />

        <size value="50" />

        <layout type="log4net.Layout.PatternLayout">

          <conversionPattern value="%level" />

        </layout>

      </parameter>

      <parameter>

        <parameterName value="@logger" />

        <dbType value="String" />

        <size value="255" />

        <layout type="log4net.Layout.PatternLayout">

          <conversionPattern value="%logger" />

        </layout>

      </parameter>

      <parameter>

        <parameterName value="@message" />

        <dbType value="String" />

        <size value="4000" />

        <layout type="log4net.Layout.PatternLayout">

          <conversionPattern value="%message" />

        </layout>

      </parameter>

      <parameter>

        <parameterName value="@exception" />

        <dbType value="String" />

        <size value="2000" />

        <layout type="log4net.Layout.ExceptionLayout" />

      </parameter>

      <parameter>

        <parameterName value="@action_name" />

        <dbType value="String" />

        <size value="4000" />

        <layout type="log4net.Layout.PatternLayout">

          <conversionPattern value="%property{action_name}" />

        </layout>

      </parameter>

      <parameter>

        <parameterName value="@line_number" />

        <dbType value="String" />

        <size value="255" />

        <layout type="log4net.Layout.PatternLayout">

          <conversionPattern value="%property{line_number}" />

        </layout>

      </parameter>

      <parameter>

        <parameterName value="@controller" />

        <dbType value="String" />

        <size value="4000" />

        <layout type="log4net.Layout.PatternLayout">

          <conversionPattern value="%property{controller}" />

        </layout>

      </parameter>

      <parameter>

        <parameterName value="@method_name" />

        <dbType value="String" />

        <size value="4000" />

        <layout type="log4net.Layout.PatternLayout">

          <conversionPattern value="%property{method_name}" />

        </layout>

      </parameter>

    </appender>

    <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender">

      <file value="Logs\web-log.txt" />

      <appendToFile value="true" />

      <rollingStyle value="Size" />

      <maxSizeRollBackups value="10" />

      <maximumFileSize value="50000KB" />

      <staticLogFileName value="true" />

      <layout type="log4net.Layout.PatternLayout">

        <conversionPattern value="%-5p %d %5rms %-22.22c{1} %-18.18M - %m%n" />

      </layout>

    </appender>

   </log4net>

 

Step 5: I create custom Exception Filter for log error in dadabase.

public class CustomExceptionHandler : HandleErrorAttribute

    {

        private static readonly ILog Logger = LogManager.GetLogger(System.Environment.MachineName);

 

        public override void OnException(ExceptionContext filterContext)

        {

            if (filterContext.ExceptionHandled || filterContext.HttpContext.IsCustomErrorEnabled)

            {

                return;

            }

            string controller = filterContext.RouteData.Values["controller"].ToString();

            string action = filterContext.RouteData.Values["action"].ToString();

            Exception e = filterContext.Exception;

            StackTrace trace = new System.Diagnostics.StackTrace(e, true);

            int lineNumber = trace.GetFrame(0).GetFileLineNumber();

            var methodName = trace.GetFrame(0).GetMethod().Name;

 

            if (action.Equals(methodName))

                methodName = DBNull.Value.ToString();

 

            GlobalContext.Properties["action_name"] = action;

            GlobalContext.Properties["controller"] = controller;

            GlobalContext.Properties["line_number"] = lineNumber;

            GlobalContext.Properties["method_name"] = methodName;

            Logger.Error(e.Message, e.GetBaseException());

 

            filterContext.ExceptionHandled = true;

 

            //this will redirect to error view in shred folder

            filterContext.Result = new ViewResult()

            {

                ViewName = "Error"

            };

        }

    }

 

Step 6: Create action method

Here, CustomExceptionHandler is custome excetion filter that log error when exception occure in this controller.

 

[CustomExceptionHandler]

    public class HomeController : Controller

    {

        public ActionResult Index()

        {

            Getdata();

            return View();

        }

        public int Getdata()

        {

            int a = 1;

            int b = 0;

            int c = 0;

            return c = a / b; //it would cause exception.  

        }

        public ActionResult About()

        {

            int a = 1;

            int b = 0;

            int c = 0;

            c = a / b; //it would cause exception.            

            return View();

        }

 

        public ActionResult Contact()

        {

            int a = 1;

            int b = 0;

            int c = 0;

            c = a / b; //it would cause exception.            

            return View();

        }

    }

Step 7: Create SQL Sript

CREATE TABLE [dbo].[Log]

( [Id] [int] IDENTITY(1,1) NOT NULL,

[Date] [datetime] NOT NULL,

[Thread] [varchar](255) NOT NULL,

[Level] [varchar](50) NOT NULL,

[Logger] [varchar](255) NOT NULL,

 [Message] [varchar](4000) NOT NULL,

[Exception] [varchar](2000) NULL,

 [ActionName] [varchar](4000) NULL,

[LineNumber] [varchar](255) NULL,

[Controller] [varchar](4000) NULL,

 [MethodName] [varchar](4000) NULL,

CONSTRAINT [PK_Log4NetLog]

PRIMARY KEY CLUSTERED ( [Id] ASC)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY]GO

 

Hope you like it. Stay tuned for more..wink

Leave a Comment

Only registered users can comment.


View Comments