Java有log4j記錄錯誤記錄檔,而asp.net可以自己寫一個來記錄錯誤記錄檔!
- 先封裝一個類
using System;using System.Collections.Generic;using System.Linq;using System.Web;
using System.IO;using System.Globalization;/// <summary>/// ErrHandler 錯誤記錄檔處理類/// </summary>public class ErrHandler{ public ErrHandler() { // // TODO: Add constructor logic here // } public static void WriteError(Exception e) { try { ///錯誤記錄檔記錄地址[每天產生一個記錄檔] string path = "~/Error/" + DateTime.Today.ToString("dd-MM-yy") + ".log"; if (!File.Exists(System.Web.HttpContext.Current.Server.MapPath(path))) { ///不存在該日誌,則建立 File.Create(System.Web.HttpContext.Current.Server.MapPath(path)).Close(); } ///寫日誌記錄 using (StreamWriter w = File.AppendText(System.Web.HttpContext.Current.Server.MapPath(path))) { w.WriteLine("Error Recode:"); w.WriteLine("\tError Time:{0}", DateTime.Now.ToString(CultureInfo.InvariantCulture)); w.WriteLine("\tError Address:" + System.Web.HttpContext.Current.Request.Url.ToString()); w.WriteLine("\tTargetSite:" + e.TargetSite); w.WriteLine("\tError Message:" + e.Message); w.WriteLine("\tError HelpLink:" + e.HelpLink); w.WriteLine("\tError StackTrace:" + e.StackTrace); w.WriteLine("************************************************************************************"); w.WriteLine("\r\n\r\n"); w.Flush(); w.Close(); } } catch (Exception ex) { WriteError(ex); } }}
2.. 類寫好了!哪裡調用呢? 建立個Global.asax檔案吧!
<%@ Application Language="C#" %><script runat="server"> void Application_Start(object sender, EventArgs e) { // Code that runs on application startup } void Application_End(object sender, EventArgs e) { // Code that runs on application shutdown } void Application_Error(object sender, EventArgs e) { //擷取最後的錯誤 Exception objErr = Server.GetLastError().GetBaseException(); // 這裡開始記錄咯 ErrHandler.WriteError(objErr);
//清除前一個錯誤
Server.ClearError(); } void Session_Start(object sender, EventArgs e) { // Code that runs when a new session is started } void Session_End(object sender, EventArgs e) { // Code that runs when a session ends. // Note: The Session_End event is raised only when the sessionstate mode // is set to InProc in the Web.config file. If session mode is set to StateServer // or SQLServer, the event is not raised. } </script>
這樣只要一發生錯誤了,都會記錄到日誌裡面! 你只需定期去檢查錯誤記錄檔了
當然你也可以在錯誤中記錄,如:
try { throw new Exception("Error"); } catch (Exception ex) { ErrHandler.WriteError(ex); }
OVER
Technorati 標籤: asp.net,error