This code example handles the application-level Error event and writes error information to the system event log. The Error event is raised whenever an application error or unhandled page error occurs.
Create an Asp.NET application-level event handler
- If your Web site does not already have a Global.asax file, create one in the root of the site.
- Create an event-handler method whose name follows the pattern Application_event. For example, to handle an application Error event, create a handler named Application_Error that takes an Object parameter and an EventArgs parameter.
void Application_Error(Object sender, EventArgs e)
{
if(!System.Diagnostics.EventLog.SourceExists
("ASPNETApplication"))
{
System.Diagnostics.EventLog.CreateEventSource
("ASPNETApplication", "Application");
}
System.Diagnostics.EventLog.WriteEntry
("ASPNETApplication",
Server.GetLastError().Message);
}
The code writes an entry to the system event log. It checks first to determine whether the event log entry named ASPNETApplication exists; if not, the code creates it. The code gets the error message associated with the error by calling the GetLastError method, and then writes the error message to the log.