WebForm 在 Global.asax 中捕獲全局異常

 1         /// <summary>
 2         /// 捕獲全局異常
 3         /// </summary>
 4         /// <param name="sender">sender</param>
 5         /// <param name="e">e</param>
 6         protected void Application_Error(Object sender, EventArgs e)
 7         {
 8             Exception ex = Server.GetLastError().GetBaseException();
 9             string ip = Request.ServerVariables.Get("HTTP_X_FORWARDED_FOR") == null ?
10                 Request.ServerVariables.Get("Remote_Addr").ToString().Trim() :
11                 Request.ServerVariables.Get("HTTP_X_FORWARDED_FOR").ToString().Trim();
12             string logpath = Server.MapPath("~/Log/" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt");
13             StringBuilder builder = new StringBuilder();
14             builder.AppendLine(string.Format("==========  {0} Application_Error BEGIN ==========", DateTime.Now));
15             builder.AppendLine("Ip:" + ip);
16             builder.AppendLine("瀏覽器:" + Request.Browser.Browser.ToString());
17             builder.AppendLine("瀏覽器版本:" + Request.Browser.MajorVersion.ToString());
18             builder.AppendLine("操做系統:" + Request.Browser.Platform.ToString());
19             builder.AppendLine("頁面:" + Request.Url.ToString());
20             builder.AppendLine("錯誤信息:" + ex.Message);
21             builder.AppendLine("錯誤源:" + ex.Source);
22             builder.AppendLine("異常方法:" + ex.TargetSite);
23             builder.AppendLine("堆棧信息:" + ex.StackTrace);
24             builder.AppendLine("==========  Application_Error END  ===================");
25 
26             lock (logpath)
27             {
28                 try
29                 {
30                     using (var writer = new StreamWriter(logpath, true))
31                     {
32                         writer.Write(builder.ToString());
33                     }
34                 }
35                 catch
36                 {
37                     // 防止寫文件時,文件被人爲打開沒法寫入等
38                     // 記錄日誌報錯不作處理,不該影響用戶繼續使用
39                 }
40             }
41 
42             Server.ClearError();
43             Response.Redirect("~/Error.htm");
44         }
相關文章
相關標籤/搜索