Monday, December 21, 2009

Custom error tracking library in asp.net using XML & C#

Being an asp.net developers we develop a web project and get it completed in a months of time as there are many organizations which works on very tight bound timeline for developing web sites Or web application projects. And delivers the project to client in months of time
While after project delivery if client come up saying that they are facing problems or application is giving errors, that time it always becomes a headache for a developer to test each things even whole project sometimes to find a smaller errors (by means of error here we are not talking about logical errors, we talking about exceptions which mostly responsible for errors in the application), there are many exceptions .net framework fires which we never come to find out while debugging or developing the application. Those exceptions never affect directly to the application but each small exception puts the unnecessary load on the server.
Here is the solution to track each and every smallest things happening inside your asp.net web application. Which I named as “Custom error tracking library
Custom error tracking library
Very first question will come is that, what is the core concept for this.                                     
Concept is like we will be maintaining an XML file with a predefined structure which I have built which will contain all the required fields as nodes and subs. Which we call as errorlog.xml
There will be a CS library file which will track each and every minor errors/exceptions happens inside the application or .net framework and will put the error details inside the XML file.
Once we got CS library ready with us we just have to a simple function with 2 overload methods as per requirement in each try/catch blocks of the code and also in Application_Error event of Global.asax file.

XML File (errorlog.xml)


xml version="1.0" encoding="utf-8"?>
<errorlog>
  <error>
    <datetime>datetimedatetime>
    <filename>filenamefilename>
    <classname>classnameclassname>
    <methodname>methodnamemethodname>
    <errormethod>errormethoderrormethod>
    <messsage>ErrorMessagemesssage>
    <errordetails>Details goes hereerrordetails>
    <IP>IP adressIP>
    <url>URLurl>
  error>
  <error>
errorlog>

Root node of XLM file will be inside root node there will be a sub node  which will get duplicated for each error. For each error, library will generate a node will all the below listed details in XML file. Next to last error node. So for each error there will be a seaprate ERROR node.
Each fields of the above XML file is descibed beloe :
1.       Datetime : date and time of the error/exception
2.       File name : file name where exception or error happens
3.       Class name : classname in which error occurred
4.       Methodname : function name where errored
5.       Errormethod : name of the function which contains error code.
6.        Message : error message/exception message
7.       Error details: detailed error description which will show whole stack trace of the functional execution.
8.       IP : client IP address  
9.       URL : absolute error ULR


CS library


There will be a CS library file where we will write all functionality for error handling and writing errors into XML file.
errorHamdler.cs file will have 2 statis methods named WriteError(), there will be 2 overloaded methods for same functions with diff. parameters.
CS file will look as given below. We name it as errorHamdler.cs

errorHandler.cs


using System;
using System.Collections.Generic;
using System.Text;
using System.Xml;
using System.Reflection;
using System.Diagnostics;
namespace code_center
{
    public class errorHandler
    {
        string _strErrorMessage, _strDetails, _strClassName, _strMethodName;
        DateTime _dtOccuranceTime = new DateTime();
        public errorHandler()
        {

        }
        public errorHandler(DateTime time, string className, string methodName, string errorMessage, string details)
        {
            _dtOccuranceTime = time;
            _strClassName = className;
            _strDetails = details;
            _strErrorMessage = errorMessage;
            _strMethodName = methodName;
        }
        public static void WriteError(Exception ex)
        {
            WriteError(ex, "");
        }
        public static void WriteError(Exception ex, string fileName)
        {
            XmlDocument doc = new XmlDocument();
            string strRootPath = System.Configuration.ConfigurationManager.AppSettings["logfilepath"].ToString();
            string xmlPath = System.Web.HttpContext.Current.Server.MapPath(strRootPath);
            doc.Load(@xmlPath);
            XmlNode newXMLNode, oldXMLNode;
            oldXMLNode = doc.ChildNodes[1].ChildNodes[0];
            newXMLNode = oldXMLNode.CloneNode(true);

            StackTrace stackTrace = new StackTrace();
            StackFrame stackFrame = stackTrace.GetFrame(1);
            MethodBase methodBase = stackFrame.GetMethod();

            newXMLNode.ChildNodes[0].InnerText = DateTime.Now.ToString();
            newXMLNode.ChildNodes[1].InnerText = fileName;
            newXMLNode.ChildNodes[2].InnerText = methodBase.DeclaringType.FullName;
            newXMLNode.ChildNodes[3].InnerText = methodBase.Name;
            newXMLNode.ChildNodes[4].InnerText = ex.TargetSite.Name;
            newXMLNode.ChildNodes[5].InnerText = ex.Message;
            newXMLNode.ChildNodes[6].InnerText = ex.StackTrace;
            newXMLNode.ChildNodes[7].InnerText = System.Web.HttpContext.Current.Request.UserHostAddress;
            newXMLNode.ChildNodes[8].InnerText = System.Web.HttpContext.Current.Request.Url.OriginalString;
            doc.ChildNodes[1].AppendChild(newXMLNode);
            doc.Save(@xmlPath);
            doc.RemoveAll();
        }
    }
}


In above code there is a line “string strRootPath = System.Configuration.ConfigurationManager.AppSettings["logfilepath"].ToString();
We need to give XML file path also where we have placed XML file in the project, so just have to add 1 line in web.config file as given below to store actual XML file path, which will be used in abiove functon.

Code inside web.config


<appSettings>
    <add key="logfilepath" value="~/errorHandling/errorlog.xml"/>   
  appSettings>

 

How to use error handler in application


Now everything is ready to be used in real time application. In each try/catch block we have to call
Writeerror() function as described below .

Code inside Default.aspx.vb


    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {

            throw new Exception("Custom error");           
        }
        catch (Exception ex)
        {
            Response.Write(ex.Message);
            code_center.errorHandler.WriteError(ex, "Default.aspx.vb");
        }
    }

Apart from each try/catch blocks we will put some code in Global.asax file also, as given below.

    void Application_Error(object sender, EventArgs e)
    {
        code_center.errorHandler.WriteError(Server.GetLastError().GetBaseException(), "Global.asax");
    }

The reason behin putting code in Global.asax file is very important and necessory as there might be many exceptions which occurs at application level and canot be tracable in any try/catch blocks in any function or events. So anyerror except try/catch blocks will come in this event (Application_Error) and will get inserted intoXML file.

That’s it, we have done with the error handling, and all errors will be tractable from the XML file which is being generated via the error handler.


No comments:

Post a Comment