Home
Manage Your Code
Snippet: Simple Global.asax Error Logger (C#)
Title: Simple Global.asax Error Logger Language: C#
Description: Simple Global.asax Error Logger Views: 92
Author: Thomas Jenkins Date Added: 8/28/2008
Copy Code  
1void Application_Error(object sender, EventArgs e)
2	{
3		Exception objErr = Server.GetLastError().GetBaseException();
4		HttpContext.Current.Response.Clear();
5
6		StringBuilder sbError = new StringBuilder();
7		sbError.AppendFormat(@"Error Caught in Application_Error event{0}", Environment.NewLine);
8		sbError.AppendFormat(@"Error in: {0} {1}", HttpContext.Current.Request.Url.ToString(), Environment.NewLine);
9		sbError.AppendFormat(@"Error Message: {0} {1}", objErr.Message.ToString(), Environment.NewLine);
10		sbError.AppendFormat(@"REMOTE_ADDR: {0} {1}", HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"], Environment.NewLine);
11		sbError.AppendFormat(@"HTTP_ACCEPT_LANGUAGE: {0} {1}", HttpContext.Current.Request.ServerVariables["HTTP_ACCEPT_LANGUAGE"], Environment.NewLine);
12		sbError.AppendFormat(@"HTTP_REFERER: {0} {1}", HttpContext.Current.Request.ServerVariables["HTTP_REFERER"], Environment.NewLine);
13		sbError.AppendFormat(@"HTTP_USER_AGENT: {0} {1}", HttpContext.Current.Request.ServerVariables["HTTP_USER_AGENT"], Environment.NewLine);
14		//sbError.AppendFormat(@"HTTP_COOKIE:  {0} {1}", HttpContext.Current.Request.ServerVariables["HTTP_COOKIE"], Environment.NewLine); 
15
16		if(objErr != null)
17			sbError.AppendFormat(@"{0}-------------------------------------------------------------------------------------------{1}Stack Trace: {2} {3}", Environment.NewLine,Environment.NewLine, objErr.StackTrace.ToString(), Environment.NewLine);
18		
19		if (!System.Diagnostics.EventLog.SourceExists("A_Application"))
20		{
21			System.Diagnostics.EventLog.CreateEventSource("A_Application", "Application");
22		}
23
24		System.Diagnostics.EventLog myLog = new System.Diagnostics.EventLog();
25		myLog.Source = "A_Application";
26		
27		myLog.WriteEntry(sbError.ToString(), System.Diagnostics.EventLogEntryType.Error);
28		Server.ClearError();
29		
30		// For test purposes, just checking how good this works
31		EmailSender email = new EmailSender(sbError.ToString());
32		
33		Server.Transfer("~/ErrorPage.aspx");
34	}