[ZT]ASP.NET利用Global.asax的Application_Error來記錄Exception訊息

 

記錄網頁Exception訊息的方法有很多種..在此介紹三種儲存方式..

1.記錄在事件檢視器

2.記錄在文字檔

3.用Email寄出訊息

asp.net(c#)

Global.asax

 

  1. <%@ Application Language="C#" %>   
  2.   
  3. <script RunAt="server">   
  4.   
  5.     void Application_Start(object sender, EventArgs e)   
  6.     {   
  7.         // 應用程式啟動時執行的程式碼   
  8.   
  9.     }   
  10.   
  11.     void Application_End(object sender, EventArgs e)   
  12.     {   
  13.         //  應用程式關閉時執行的程式碼   
  14.   
  15.     }   
  16.   
  17.     void Application_Error(object sender, EventArgs e)   
  18.     {   
  19.         string Message = "";   
  20.         Exception ex = Server.GetLastError();   
  21.         Message = "發生錯誤的網頁:{0}錯誤訊息:{1}堆疊內容:{2}";   
  22.         Message = String.Format(Message, Request.Path + Environment.NewLine, ex.GetBaseException().Message + Environment.NewLine, Environment.NewLine + ex.StackTrace);   
  23.   
  24.         //寫入事件撿視器,方法一   
  25.         System.Diagnostics.EventLog.WriteEntry("WebAppError", Message, System.Diagnostics.EventLogEntryType.Error);   
  26.   
  27.         //寫入文字檔,方法二   
  28.         System.IO.File.AppendAllText(Server.MapPath(string.Format("Log\\{0}.txt", DateTime.Now.Ticks.ToString())), Message);   
  29.   
  30.         //寄出Email,方法三   
  31.         //此方法請參考System.Net.Mail.MailMessage   
  32.   
  33.         //清除Error   
  34.         Server.ClearError();   
  35.   
  36.         Response.Write("系統錯誤,請聯絡系統管理員!!");   
  37.   
  38.     }   
  39.   
  40.     void Session_Start(object sender, EventArgs e)   
  41.     {   
  42.         // 啟動新工作階段時執行的程式碼   
  43.   
  44.     }   
  45.   
  46.     void Session_End(object sender, EventArgs e)   
  47.     {   
  48.         // 工作階段結束時執行的程式碼。    
  49.         // 注意: 只有在 Web.config 檔將 sessionstate 模式設定為 InProc 時,   
  50.         // 才會引發 Session_End 事件。如果將工作階段模式設定為 StateServer    
  51.         // 或 SQLServer,就不會引發這個事件。   
  52.   
  53.     }   
  54.           
  55. </script>  

 

 

測試網頁,產生一個Null Exception

  1. protected void Page_Load(object sender, EventArgs e)   
  2. {   
  3.     throw (new ArgumentNullException());   
  4. }  

 

執行結果:

事件檢視器

文字檔

參考網址:

http://www.blueshop.com.tw/board/show.asp?subcde=BRD20080822113331G86&fumcde=FUM20041006161839LRJ
http://support.microsoft.com/kb/306355/zh-tw

 

 

引用URL

http://www.dotblogs.com.tw/puma/archive/2008/08/31/5260.aspx  複製網址
posted on 2009-04-17 20:15  巍巍边疆  阅读(954)  评论(0编辑  收藏  举报