65.9K
CodeProject 正在变化。 阅读更多。
Home

在 Windows 事件查看器中记录应用程序错误详情

emptyStarIconemptyStarIconemptyStarIconemptyStarIconemptyStarIcon

0/5 (0投票)

2013 年 10 月 11 日

CPOL

1分钟阅读

viewsIcon

12803

Global.asax 是 Web 应用程序中的全局文件,它提供应用程序级别的事件注册。 此文件中包含许多事件

Global.asax 是 Web 应用程序中的全局文件,它提供应用程序级别的事件注册。 此文件中的许多事件可用于特定目的。“Application_Error”是在应用程序中发生未处理异常时触发的事件。 重要的是,如果未在此事件中处理该未处理异常,则会向应用程序的用户显示异常摘要页面。 这会使他感到困惑,并对应用程序感到不确定。 因此,始终最好在此事件中处理未处理的异常。

本文将重点不仅在于处理“Application_Error”事件中的异常,还在于将异常详情记录到“事件查看器”中。

public class Global : System.Web.HttpApplication
{

protected void Application_Error(object sender, EventArgs e)
{
try
{
// gets the error occured
Exception ex = Server.GetLastError().GetBaseException();

// checks if the event source is registered
if (!System.Diagnostics.EventLog.SourceExists(".NET Runtime"))
{
System.Diagnostics.EventLog.CreateEventSource(".NET Runtime", "Application");
}

//log the details of the error occured
System.Diagnostics.EventLog log = new System.Diagnostics.EventLog();
log.Source = ".NET Runtime";
log.WriteEntry(String.Format("\r\n\r\nApplication Error\r\n\r\n" +
"MESSAGE: {0}\r\n" +
"SOURCE: {1}\r\n" +
"FORM: {2}\r\n" +
"QUERYSTRING: {3}\r\n" +
"TARGETSITE: {4}\r\n" +
"STACKTRACE: {5}\r\n",
ex.Message,
ex.Source,
Request.Form.ToString(),
Request.QueryString.ToString(),
ex.TargetSite,
ex.StackTrace),
System.Diagnostics.EventLogEntryType.Error);

Server.ClearError();
}
catch
{
// in case of exception occured in log
Server.ClearError();
}
}

protected void Application_Start(object sender, EventArgs e)
{

}
protected void Application_End(object sender, EventArgs e)
{

}
}

 

“Application_Error”事件中的代码首先从服务器对象检索当前发生的异常,以便将其详细信息写入事件查看器日志。“System.Diagnostics.EventLog”可以写入事件查看器中的日志详细信息。 它创建事件源,以便在事件源不存在的情况下写入事件消息,然后使用 EventLog 对象,将格式化的详细消息写入事件查看器。“Server.ClearError()”清除先前发生的异常。

 

© . All rights reserved.