標籤:tla cto 堆棧 問題 add 自動 存在 nsf bsp
當我們將網站布署到線上之後,為了即時瞭解網站的運行情況,如是否有錯誤頁面、網站運行速度、是否有攻擊等。那麼我們就很有必要為網站加上錯誤與異常記錄到記錄檔,這樣就可以隨時查看網站的線上運行情況,另有一個好處是當網站有運行錯誤頁面時,根據錯誤記錄檔我們可以快速到定位到錯誤行進行排查原因、解決問題,這個是對於運行線上上而不能調試的網站的一個非常有必要的功能。
具體實現方法:
在通用檔案Global.asax.cs中添加Application_Error的方法。只要當程式有錯誤時程式就會自動執行該方法,從而記錄到錯誤記錄檔。
void Application_Error(object sender, EventArgs e){ //在出現未處理的錯誤時啟動並執行代碼 Exception ex = Server.GetLastError().GetBaseException(); string errorTime = "異常時間:" + DateTime.Now.ToString(); string errorAddress = "異常地址:" + Request.Url.ToString(); string errorInfo = "異常資訊:" + ex.Message; string errorSource = "錯誤源:" + ex.Source; string errorType = "運行類型:" + ex.GetType(); string errorFunction = "異常函數:" + ex.TargetSite; string errorTrace = "堆棧資訊:" + ex.StackTrace; Server.ClearError(); System.IO.StreamWriter writer = null; try { lock (this) { //寫入日誌 string path = string.Empty; path = Server.MapPath("~/ErrorLogs/"); //不存在則建立錯誤記錄檔檔案夾 if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } path +=string.Format(@"\{0}.txt", DateTime.Now.ToString("yyyy-MM-dd")); writer = !File.Exists(path) ? File.CreateText(path) : File.AppendText(path); //判斷檔案是否存在,如果不存在則建立,存在則添加 writer.WriteLine("使用者IP:" + Request.UserHostAddress); writer.WriteLine(errorTime); writer.WriteLine(errorAddress); writer.WriteLine(errorInfo); writer.WriteLine(errorSource); writer.WriteLine(errorType); writer.WriteLine(errorFunction); writer.WriteLine(errorTrace);writer.WriteLine("********************************************************************************************"); } } finally { if (writer != null) { writer.Close(); } } Server.Transfer("~/500webpage.aspx"); //跳轉到顯示友好錯誤的頁面}
C#錯誤異常日誌記錄到檔案