技术开发 频道

Enterprise Library 2.0:记录站点中未处理的异常

    3.捕获并记录ASP.NET异常

    首先需要添加如下引用:

Microsoft.Practices.EnterpriseLibrary.Logging.dll Microsoft.Practices.EnterpriseLibrary.Logging.Database.dll Microsoft.Practices.EnterpriseLibrary.Data.dll

    为Web站点添加Global.asax文件,并且在Application_Error编写如下代码,这样在有异常发生时应用程序块会把异常信息记录到数据库中:

<%@ Application Language="C#" %> <%@ Import Namespace="Microsoft.Practices.EnterpriseLibrary.Logging" %> <script runat="server"> void Application_Error(object sender, EventArgs e) { // Code that runs when an unhandled error occurs Exception ex = Server.GetLastError().GetBaseException(); LogEntry log = new LogEntry(); log.Message = ex.Message + "\r\nSOURCE: " + ex.Source + "\r\nFORM: " + Request.Form.ToString() + "\r\nQUERYSTRING: " + Request.QueryString.ToString() + "\r\nTARGETSITE: " + ex.TargetSite + "\r\nSTACKTRACE: " + ex.StackTrace; Logger.Write(log); } </script><%@ Application Language="C#" %> <%@ Import Namespace="Microsoft.Practices.EnterpriseLibrary.Logging" %> <script runat="server"> void Application_Error(object sender, EventArgs e) { // Code that runs when an unhandled error occurs Exception ex = Server.GetLastError().GetBaseException(); LogEntry log = new LogEntry(); log.Message = ex.Message + "\r\nSOURCE: " + ex.Source + "\r\nFORM: " + Request.Form.ToString() + "\r\nQUERYSTRING: " + Request.QueryString.ToString() + "\r\nTARGETSITE: " + ex.TargetSite + "\r\nSTACKTRACE: " + ex.StackTrace; Logger.Write(log); } </script>

    4.创建一个未处理的异常

    在Default.aspx.cs的Page_Load事件中制造一个异常信息

public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { int error = Int32.Parse("bbbbb"); } }

    运行程序后,可以看到数据库表中会多出一条记录:

    其中Message的内容:

Input string was not in a correct format. SOURCE: mscorlib FORM: QUERYSTRING: TARGETSITE: Void StringToNumber(System.String, System.Globalization.NumberStyles, NumberBuffer ByRef, System.Globalization.NumberFormatInfo, Boolean) STACKTRACE: at System.Number.StringToNumber(String str, NumberStyles options, NumberBuffer& number, NumberFormatInfo info, Boolean parseDecimal) at System.Number.ParseInt32(String s, NumberStyles style, NumberFormatInfo info) at System.Int32.Parse(String s) at _Default.Page_Load(Object sender, EventArgs e) in c:\Inetpub\wwwroot\EntLibDemo2\Default.aspx.cs:line 15 at System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e) at System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e) at System.Web.UI.Control.OnLoad(EventArgs e) at System.Web.UI.Control.LoadRecursive() at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)


    这样我们就实现了用Logging Application Block对未处理异常信息的记录,如果要记录到文本文件或者发送Email,只需要在第2步新建Flat File Trace Listener或者Email Trace Listener,使用文本文件时要注意设置文件夹的权限。

0
相关文章