1. 程式人生 > >net錯誤日誌統一處理 Global.asax

net錯誤日誌統一處理 Global.asax

webform錯誤日誌統一處理 Global.asax

        protected void Application_Error(object sender, EventArgs e)
        {
            //在出現未處理的錯誤時執行的程式碼
            //在出現未處理的錯誤時執行的程式碼
            Exception objErr = Server.GetLastError().GetBaseException();
            string error = string.Empty;
            string errortime = string.Empty
; string erroraddr = string.Empty; string errorinfo = string.Empty; string errorsource = string.Empty; string errortrace = string.Empty; error += "發生時間:" + System.DateTime.Now.ToString() + "<br>"; errortime = "發生時間:" + System.DateTime
.Now.ToString(); error += "發生異常頁: " + Request.Url.ToString() + "<br>"; erroraddr = "發生異常頁: " + Request.Url.ToString() + "?action=" + (Request["action"] ?? ""); error += "異常資訊: " + objErr.Message + "<br>"; errorinfo = "異常資訊: " + objErr.Message
; errorsource = "錯誤幫助資訊:" + objErr.HelpLink; errortrace = "堆疊資訊:" + objErr.StackTrace; error += "--------------------------------------<br>"; Server.ClearError(); Application["error"] = error; //獨佔方式,因為檔案只能由一個程序寫入. System.IO.StreamWriter writer = null; try { lock (this) { // 寫入日誌 string year = DateTime.Now.Year.ToString(); string month = DateTime.Now.Month.ToString(); string path = string.Empty; string filename = DateTime.Now.Day.ToString() + ".html"; path = Server.MapPath("~/ErrorLog1872/") + year + "/" + month; //如果目錄不存在則建立 if (!System.IO.Directory.Exists(path)) { System.IO.Directory.CreateDirectory(path); } System.IO.FileInfo file = new System.IO.FileInfo(path + "/" + filename); //檔案不存在就建立,true表示追加 writer = new System.IO.StreamWriter(file.FullName, true); string ip = "使用者IP:" + Request.UserHostAddress; string line = "-----------------------------------------------------"; string log = "<p style='font-size:9pt;'><br>" + line + "<br><font color=red>" + errortime + "&nbsp;&nbsp;" + erroraddr + "</font><br><font color=green>" + "<br/>" + ip + errorinfo + "<br>" + errorsource + "<br>" + errortrace.Replace("\r\n", "<br>") + "</font></p>"; writer.WriteLine(log); } } finally { if (writer != null) writer.Close(); } Response.Write("{\"ret\":-1}"); Response.End(); }

MVC錯誤資訊統一處理
首先在App_Start裡面新建一個類MyExceptionFilterAttribute.cs,繼承HandleErrorAttribute,重寫OnException方法。
修改App_Start/FilterConfig.cs

 public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            //filters.Add(new HandleErrorAttribute());
            filters.Add(new MyExceptionFilterAttribute());  
        }
public class MyExceptionFilterAttribute : HandleErrorAttribute 
    {
        public override void OnException(ExceptionContext filterContext)
        {
            var dt = DateTime.Now;
            var logPath = HttpContext.Current.Server.MapPath("/errorlog/" + dt.ToString("yyyy-MM"));
            if (!Directory.Exists(logPath))
            {
                Directory.CreateDirectory(logPath);
            }
            var logFilePath = string.Format("{0}/{1}.txt", logPath, dt.ToString("yyyy-MM-dd"));
            StreamWriter writer = null;
            try
            {
                writer = new StreamWriter(logFilePath, true, Encoding.UTF8);
                writer.WriteLine("------------------------------------------------------------------------------");
                writer.WriteLine("出錯時間:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
                writer.WriteLine("錯誤資訊:" + filterContext.Exception.Message);
                writer.WriteLine("Controller:" + filterContext.Controller);
                writer.WriteLine("錯誤源:" + filterContext.Exception.Source);
                writer.WriteLine("堆疊資訊:" + filterContext.Exception.StackTrace);
                writer.WriteLine("------------------------------------------------------------------------------");
            }
            catch
            {
            }
            finally
            {
                if (writer != null)
                {
                    writer.Close();
                }
            }
        }  
    }