Generic Error Logger using ASP.Net & C#

By default this file has following event list:

  1. void Application_Start(object sender, EventArgs e)  
  2. {  
  3.     // Code that runs on application startup  
  4. }  
  5. void Application_End(object sender, EventArgs e)  
  6. {  
  7.     //  Code that runs on application shutdown  
  8. }  
  9. void Application_Error(object sender, EventArgs e)  
  10. {  
  11.     // Code that runs when an unhandled error occurs  
  12.     ErrorHandler objErrHandler = new ErrorHandler();  
  13.     objErrHandler.Cur_RedirectPath = "./ErrorForm.aspx?ErrorMessage=";  
  14.     objErrHandler.Cur_Response = Response;  
  15.     objErrHandler.Cur_ServerUtil = Server;  
  16.     objErrHandler.DoHandleError();              
  17.     objErrHandler.LogError(ConfigurationManager.AppSettings["filePath"]);  
  18. }  
  19. void Session_Start(object sender, EventArgs e)  
  20. {  
  21.     // Code that runs when a new session is started  
  22. }  
  23. void Session_End(object sender, EventArgs e)  
  24. {  
  25.     // Code that runs when a session ends.  
  26.     // Note: The Session_End event is raised only when the sessionstate mode  
  27.     // is set to InProc in the Web.config file. If session mode is set to StateServer  
  28.     // or SQLServer, the event is not raised.  
  29. }  
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:

  1. using System;  
  2. using System.Data;  
  3. using System.Configuration;  
  4. using System.Web;  
  5. using System.Web.Security;  
  6. using System.Web.UI;  
  7. using System.Web.UI.WebControls;  
  8. using System.Web.UI.WebControls.WebParts;  
  9. using System.Web.UI.HtmlControls;  
  10. using System.Text;  
  11. using System.IO;  
  12. /// <summary>  
  13. /// Summary description for ErrorHandler  
  14. /// </summary>  
  15. public class ErrorHandler  
  16. {  
  17.     public string strShortMessage = "";  
  18.     string strErrLog = "";  
  19.     private string Redirect_Path = "";  
  20.     private HttpResponse Http_Response;  
  21.     private HttpServerUtility Http_ServerUtil;  
  22.     string buildPath = "";  
  23.     String strMessage = "";  
  24.     public string Cur_RedirectPath  
  25.     {  
  26.         get { return Redirect_Path; }  
  27.         set { Redirect_Path = value; }  
  28.     }  
  29.     public HttpResponse Cur_Response  
  30.     {  
  31.         get { return Http_Response; }  
  32.         set { Http_Response = value; }  
  33.     }  
  34.     public HttpServerUtility Cur_ServerUtil  
  35.     {  
  36.         get { return Http_ServerUtil; }  
  37.         set { Http_ServerUtil = value; }  
  38.     }  
  39.     public void DoHandleError()  
  40.     {  
  41.         Exception ex = Http_ServerUtil.GetLastError().GetBaseException();  
  42.         strMessage = "MESSAGE: " + ex.Message + "<br/>";  
  43.         strMessage = strMessage + " SOURCE: " + ex.Source + "<br/>";  
  44.         strMessage = strMessage + " TARGETSITE: " + ex.TargetSite + "<br>";  
  45.         strMessage = strMessage + " STACK TRACE: " + ex.StackTrace + "<br/>";  
  46.         strMessage = strMessage + " DATA: " + ex.Data + "<br/>";  
  47.         strMessage = strMessage + " INNER EXCEPTION: " + ex.InnerException + "<br/></font>";  
  48.         strErrLog = "Date: " + DateTime.Now + " Strace: " + ex.StackTrace;  
  49.         strShortMessage = ex.Message.Substring(0, ex.Message.IndexOf("."));  
  50.         if (Redirect_Path.Contains("?"))  
  51.         {  
  52.             Http_Response.Redirect(Redirect_Path + strShortMessage);  
  53.         }  
  54.         else  
  55.         {  
  56.             Http_Response.Redirect(Redirect_Path);  
  57.         }  
  58.         //CLEAR ERROR  
  59.         Http_ServerUtil.ClearError();  
  60.     }  
  61.     //LOG ERROR TO SOME FILE  
  62.     public void LogError(string strFilePath)  
  63.     {  
  64.         buildPath = DateTime.Now.Day + "_" + DateTime.Now.Month + "_" + DateTime.Now.Year;  
  65.         string filePath = strFilePath + "\\" + buildPath + ".txt";  
  66.         if (!(File.Exists(filePath)))  
  67.         {  
  68.             StreamWriter sw;  
  69.             sw = File.CreateText(filePath);  
  70.             //sw.WriteLine(strErrLog);  
  71.             sw.WriteLine(strMessage);  
  72.             sw.WriteLine("----------------------------------------");  
  73.             sw.Close();  
  74.         }  
  75.         else  
  76.         {  
  77.             File.AppendAllText(filePath, strErrLog);  
  78.         }  
  79.     }  
  80. }  

 

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

  1. protected void Page_Load(object sender, EventArgs e)  
  2. {  
  3.     Response.Redirect("./SomePage.aspx");  
  4. }  
As we are using unique page "ErrorForm.aspx" to display short message so on the similar page we have to write the following code.
  1. protected void Page_Load(object sender, EventArgs e)  
  2. {  
  3.     if (Request.QueryString["ErrorMessage"] != null && Request.QueryString["ErrorMessage"].Trim() != "")  
  4.     {  
  5.         lblMessage.Text = Request.QueryString["ErrorMessage"].ToString();  
  6.     }  
  7. }  
A developer can extend this functionality to write into 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.


Similar Articles