Click here to Skip to main content
15,886,781 members
Articles / Web Development / ASP.NET

Custom Error Tracking Library in ASP.NET using XML & C#

Rate me:
Please Sign up or sign in to vote.
3.92/5 (9 votes)
24 Mar 2010CPOL4 min read 42.6K   21   19
Custom error tracking library in ASP.NET using XML and C#

Being an ASP.NET developer, we develop a web project and get it completed in a months time as there are many organizations which work on very tight bound timelines for developing web sites or web application projects and deliver the project to the client in months.

While after project delivery, if client comes up saying that they are facing problems or that the application is giving errors, that time it always becomes a headache for a developer to test each thing even whole project sometimes to find smaller errors (by means of error here, we are not talking about logical errors, we are talking about exceptions which are mostly responsible for errors in the application). There are many exceptions that the .NET Framework fires which we never come to find out while debugging or developing the application. Those exceptions never directlyaffect the application but each small exception puts the unnecessary load on the server.

Here is the solution to track each and every small thing happening inside your ASP.NET web application, which I named as “Custom error tracking library”.

Custom error tracking library

The very first question that will come is "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 error/exception that happens inside the application or .NET Framework and will put the error details inside the XML file.

Once we got the CS library ready with us, we just have a simple function with 2 overload methods as per the requirement in each try/catch block of the code and also in Application_Error event of Global.asax file.

XML File (errorlog.xml)

XML
<xml version="1.0″ encoding="utf-8″>
<errorlog>
  <error>
    <datetime>datetime</datetime>
    <filename>filename</filename>
    <classname>classname</classname>
    <methodname>methodname</methodname>
    <errormethod>errormethod</errormethod>
    <messsage>ErrorMessage</messsage>
    <errordetails>Details goes here</errordetails>
    <IP>IP address</IP>
    <url>URL</url>
  </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 with all the below listed details in XML file. Next to last error node. So for each error, there will be a separate ERROR node.

Each field of the above XML file is descibed below:

  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 error occurred
  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 URL

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 static methods named WriteError(), there will be 2 overloaded methods for same functions with different parameters.

CS file will look as given below. We name it as errorHamdler.cs.

errorHandler.cs

C#
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 the above code, there is a line:

C#
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 the actual XML file path, which will be used in the above function.

Code Inside web.config

ASP.NET
<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

C#
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 block, we will put some code in Global.asax file also, as given below:

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

The reason behind putting code in Global.asax file is very important and necessary as there might be many exceptions which occur at the application level and cannot be traceable in any try/catch blocks in any function or events. So any error except try/catch blocks will come in this event (Application_Error) and will get inserted into XML file.

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

This article was originally posted at http://kirandangar.blogspot.com/feeds/posts/default

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior) Gateway Technolabs Pvt. Ltd
India India
Having 4+ years of Technical Experience in asp.net,c#.net, SQL Server 2008,AJAX, XML,JQuery, JavaScript, .net framework, WCF, WPF/Silverlight,SSIS, SSRS, asp.net MVC.

While not working loves Photography and bike riding. Playing computer games are the best stress buster for him Smile | :)

Comments and Discussions

 
QuestionNice Pin
JQuery Geeks21-Oct-11 19:00
JQuery Geeks21-Oct-11 19:00 
AnswerRe: Nice Pin
kiran dangar21-Oct-11 19:01
kiran dangar21-Oct-11 19:01 
GeneralMy vote of 1 Pin
EngleA30-Mar-10 3:35
EngleA30-Mar-10 3:35 
GeneralRe: My vote of 1 Pin
kiran dangar4-Oct-11 2:01
kiran dangar4-Oct-11 2:01 
Rantwow Pin
EngleA30-Mar-10 3:17
EngleA30-Mar-10 3:17 
GeneralRe: wow Pin
kiran dangar4-Oct-11 2:15
kiran dangar4-Oct-11 2:15 
GeneralRe: wow Pin
EngleA4-Oct-11 3:38
EngleA4-Oct-11 3:38 
GeneralMy vote of 1 Pin
Richard Schneider (HP NZ)25-Mar-10 13:11
Richard Schneider (HP NZ)25-Mar-10 13:11 
use log4net
GeneralRe: My vote of 1 Pin
kiran dangar23-Oct-11 19:28
kiran dangar23-Oct-11 19:28 
GeneralWhy to reinvent the wheel Pin
Deepak Davesar17-Feb-10 22:17
Deepak Davesar17-Feb-10 22:17 
GeneralRe: Why to reinvent the wheel Pin
kiran dangar23-Oct-11 19:28
kiran dangar23-Oct-11 19:28 
GeneralNope !! Pin
pdchowdary1-Feb-10 18:20
pdchowdary1-Feb-10 18:20 
GeneralRe: Nope !! Pin
kiran dangar4-Oct-11 2:21
kiran dangar4-Oct-11 2:21 
GeneralNot the best way Pin
Bibhas Paul28-Jan-10 16:49
Bibhas Paul28-Jan-10 16:49 
GeneralRe: Not the best way Pin
kiran dangar28-Jan-10 22:06
kiran dangar28-Jan-10 22:06 
QuestionShouldn't XmlSerializer make this much easier? Pin
jpluimers25-Jan-10 23:39
jpluimers25-Jan-10 23:39 
AnswerRe: Shouldn't XmlSerializer make this much easier? Pin
kiran dangar28-Jan-10 22:08
kiran dangar28-Jan-10 22:08 
General:) Pin
Rakesh Kapuriya20-Jan-10 1:19
Rakesh Kapuriya20-Jan-10 1:19 
GeneralRe: :) Pin
kiran dangar20-Jan-10 2:33
kiran dangar20-Jan-10 2:33 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.