Tuesday, December 19, 2006

ASP.Net unhandled exception logging

Here is a snippet of code that can be added to your Global.asax file that will log all errors that are not handled in your ASP.Net application. The results in this example are logged to a separate log called “FrontLine Web App” (other options would be Application or System or whatever your custom name is) and the source for the entries in that log are logged as “FrontLine Web App” as well.

void Application_Error(object sender, EventArgs e)

{

// Code that runs when an unhandled error occurs

Exception objErr = Server.GetLastError().GetBaseException();

string logName = "FrontLine Web App";

if (!EventLog.SourceExists(logName))

{

// Note: we are writing to a special FrontLine Web App log

//(specified in second param)

EventLog.CreateEventSource(logName, logName);

}

EventLog log = new EventLog();

log.Source = logName;

// write the error to the Event Log

string err = "Error Caught in Application_Error event\n" +

"Error in: " + Request.Url.ToString() +

"\nError Message:" + objErr.Message.ToString() +

"\nStack Trace:" + objErr.StackTrace.ToString();

log.WriteEntry(err, EventLogEntryType.Error);

}

Also, you will probably want to include the following line in your web config so that end users won’t see the actual unhandled exception, it will just show a custom error page.

<customErrors mode="On" defaultRedirect="FriendlyErrorPage.aspx" />

No comments: