Simple Error Logging Mecanism In .Net Using Log4Net

What is Error Logging ?

Exception Handling is a very important concept in software development. It does not matter how efficiently and optimized code you are writing, there is one thing you can not ignore it and that is an Exception.

There are various ways for logging errors, here I will be showing you one of the simplest way to log error/exception using Log4Net. I will only explain how to code it in your code snippet and will not go through its concepts. If you want some more knowledge then here is a link you can go for it.

Here is the sample project you can download it and check.

   Download Source Code Here

Example on Error Logging Mechanism in .NET

Lets consider a condition where an exception can be produce. OK, lets take the simple and common one Attempted to divide by zero.

Every time you try to divide a number by 0 it will give an exception Attempted to divide by zero.

Step 1

Just take a simple web form and add a reference to the log4net dll.(Download the demo project and you will find the dll inside the bin folder.)

I have taken a button and on clicking on it I m trying to generate the Attempted to divide by zero exception.

Step 2

Now take a new class file and give it a name of Logging and add it to the project. Put the below code in this class.

  internal static readonly ILog log = LogManager.GetLogger

        /// <summary>
        /// Log the Exceptions
        /// </summary>
        /// <param name="ex">Exception</param>
        public static void LogError(Exception ex)
                log.Info("<br/><hr/>Log Entry<hr/> ");
                log.Error(string.Format("<br/><b>Error Message : </b>{0}", ex.Message));
                log.Error(string.Format("<br/><b>Error StackTrace : </b>{0}", ex.StackTrace));

                //Log inner exceptions.
                while (ex.InnerException != null)
                    ex = ex.InnerException;
                    log.Error("<hr/><b>Inner Exception : </b>");
                    log.Error(string.Format("<br/>Error Message : {0}", ex.Message));
                    log.Error(string.Format("<br/>Error StackTrace : {0}", ex.StackTrace));


            catch (Exception logex)
** Here in the while loop I am trying to iterate the exception if there is any inner exceptions.

Step 3

Just add the below line of code in the AssemblyInfo.cs class present in the Properties folder.
[assembly: log4net.Config.XmlConfigurator(Watch = true)

Step 4

Now add the below things to the web config file
 <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/>
** Add this in the configSections

And then add the below code inside configuration.
    <appender name="FileAppender" type="log4net.Appender.FileAppender">
      <file value="Errors/error.html"/>
      <appendToFile value="true"/>
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date - %message%newline"/>
      <level value="INFO"/>
      <appender-ref ref="ConsoleAppender"/>
      <appender-ref ref="FileAppender"/>
      <appender-ref ref="RollingLogFileAppender"/>
** this will create a folder named Errors in the root folder and then will add a html file named error.html for the first time to write the error. Next time it will append the error.html file with new exceptions.

Step 5

OK we are almost done just generate an exception in the web form and log it. Just add the below code and go to the browser and click the button. Here you will catch an exception which will be logged in the error.html file in Errors folder.
 protected void btnLogError_OnClick(object sender, EventArgs e)
            int num1 = 10;
            int num2 = 0;
            int num3;

            num3 = num1 / num2;

        catch (Exception ex)
Now we ave successfully logged the error using log4net.
This is a working example of error logging mechanisim. you can download the source code from the above link.

Happy Coding...

No comments:

Post a Comment