Generic Error Logger using ASP.Net & C#


By default this file has following event list:

void Application_Start(object sender, EventArgs e)

{

    // Code that runs on application startup

}

 

void Application_End(object sender, EventArgs e)

{

    //  Code that runs on application shutdown

}

 

void Application_Error(object sender, EventArgs e)

{

    // Code that runs when an unhandled error occurs

    ErrorHandler objErrHandler = new ErrorHandler();

    objErrHandler.Cur_RedirectPath = "./ErrorForm.aspx?ErrorMessage=";

    objErrHandler.Cur_Response = Response;

    objErrHandler.Cur_ServerUtil = Server;

    objErrHandler.DoHandleError();            

   objErrHandler.LogError(ConfigurationManager.AppSettings["filePath"]);

}


void Session_Start(object sender, EventArgs e)

{

    // Code that runs when a new session is started

}


void Session_End(object sender, EventArgs e)

{

    // Code that runs when a session ends.

    // Note: The Session_End event is raised only when the sessionstate mode

    // is set to InProc in the Web.config file. If session mode is set to StateServer

    // or SQLServer, the event is not raised.

}

Which runs at the server side:

Many times I have observed that while accessing site/portal some error occurs and it displays entire message on the site. This article will help you in avoiding such errors.

"Application_Error" that occurs when an error occurs, we can trap this error and redirect to some specific aspx file. In this article, I am generating log text file which will have all the details of the errors and redirect to user to "ErrorForm.aspx" file with the short error message.

To do this I have a "Util.cs" class which is as below:

using System;

using System.Data;

using System.Configuration;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Web.UI.HtmlControls;

using System.Text;

using System.IO;

/// <summary>

/// Summary description for ErrorHandler

/// </summary>

public class ErrorHandler

{

    public string strShortMessage = "";

    string strErrLog = "";

    private string Redirect_Path = "";

    private HttpResponse Http_Response;

    private HttpServerUtility Http_ServerUtil;

    string buildPath = "";

    String strMessage = "";

    public string Cur_RedirectPath

    {

        get { return Redirect_Path; }

        set { Redirect_Path = value; }

    }

    public HttpResponse Cur_Response

    {

        get { return Http_Response; }

        set { Http_Response = value; }

    }

    public HttpServerUtility Cur_ServerUtil

    {

        get { return Http_ServerUtil; }

        set { Http_ServerUtil = value; }

    }

 

    public void DoHandleError()

    {

        Exception ex = Http_ServerUtil.GetLastError().GetBaseException();

        strMessage = "MESSAGE: " + ex.Message + "<br/>";

        strMessage = strMessage + " SOURCE: " + ex.Source + "<br/>";

        strMessage = strMessage + " TARGETSITE: " + ex.TargetSite + "<br>";

        strMessage = strMessage + " STACK TRACE: " + ex.StackTrace + "<br/>";

        strMessage = strMessage + " DATA: " + ex.Data + "<br/>";

        strMessage = strMessage + " INNER EXCEPTION: " + ex.InnerException + "<br/></font>";

        strErrLog = "Date: " + DateTime.Now + " Strace: " + ex.StackTrace;

        strShortMessage = ex.Message.Substring(0, ex.Message.IndexOf("."));

        if (Redirect_Path.Contains("?"))

        {

            Http_Response.Redirect(Redirect_Path + strShortMessage);

        }

        else

        {

            Http_Response.Redirect(Redirect_Path);

        }

        //CLEAR ERROR

        Http_ServerUtil.ClearError();

    }

    //LOG ERROR TO SOME FILE

    public void LogError(string strFilePath)

    {

        buildPath = DateTime.Now.Day + "_" + DateTime.Now.Month + "_" + DateTime.Now.Year;

        string filePath = strFilePath + "\\" + buildPath + ".txt";

        if (!(File.Exists(filePath)))

        {

            StreamWriter sw;

            sw = File.CreateText(filePath);

            //sw.WriteLine(strErrLog);

            sw.WriteLine(strMessage);

            sw.WriteLine("----------------------------------------");

            sw.Close();

        }

        else

        {

            File.AppendAllText(filePath, strErrLog);

        }

    }

}


To show a demonstration on default.aspx page I am redirecting to such a page which does not exists in the system, and system will generate error message, which is getting logged in to the text file in same folder.

Here is "Default.aspx" page code

protected void Page_Load(object sender, EventArgs e)

{

    Response.Redirect("./SomePage.aspx");
}

As we are using unique page "ErrorForm.aspx" to display short message so on the similar page we have to write following code.

protected void Page_Load(object sender, EventArgs e)

{

    if (Request.QueryString["ErrorMessage"] != null && Request.QueryString["ErrorMessage"].Trim() != "")

    {

        lblMessage.Text = Request.QueryString["ErrorMessage"].ToString();

    }
}

Developer can extend this functionality to write in to some database table if required or can generate email functionality and extend this article.

Note: Again in this article also as system creates text file and write all the log to this file, we should have is ASPNET user should have full control on this folder.

Up Next
    Ebook Download
    View all
    Learn
    View all