在Web應用運行過程中,我們難免會遇到程序運行異常,這個時候我們就應該將異常信息記錄下來,以便開發人員和維護人員對異常原因進行還原,對異常原因進行修復。在ASP.NET平臺中進行日志記錄的組件也有很多,如Log4Net、CommonLogging等,我們這里選用Log4Net進行異常日志的記錄。
1. 捕獲異常
在ASP.NET MVC中提供了一個全局的異常處理過濾器:HandleErrorAttribute,可以通過該過濾器捕獲異常信息。
我們在Models文件夾下新建類型Log4ExceptionAttribute,繼承HandleErrorAttribute類,同時重寫OnException方法來捕獲異常數據:
using System.Web.Mvc;namespace PMS.WebApp.Models{ public class Log4ExceptionAttribute:HandleErrorAttribute { /// <summary> /// 重寫OnException方法來捕獲異常數據 /// </summary> /// <param name="filterContext"></param> public override void OnException(ExceptionContext filterContext) { base.OnException(filterContext); //捕獲當前異常數據 var ex = filterContext.Exception; } }}
新建過濾器后我們還需要在Global文件中調用的RegisterGlobalFilters方法中完成自己定義異常處理過濾的注冊。
using System.Web.Mvc;using PMS.WebApp.Models;namespace PMS.WebApp{ public class FilterConfig { public static void RegisterGlobalFilters(GlobalFilterCollection filters) { //filters.Add(new HandleErrorAttribute()); filters.Add(new Log4ExceptionAttribute()); } }}
2. 考慮到多用戶并發操作時可能產生的問題,我們需要新建一個隊列來進行異常信息的暫存,同時開辟一個線程專門對隊列中的異常信息進行處理。
在Log4ExceptionAttribute類中新建一個靜態的異常類型的隊列,在發生異常后,程序自動觸發OnException方法,方法中將當前的異常信息入隊后,跳轉到錯誤頁面。
using System;using System.Collections.Generic;using System.Web.Mvc;namespace PMS.WebApp.Models{ public class Log4ExceptionAttribute:HandleErrorAttribute { public static Queue<Exception> Exceptions=new Queue<Exception>(); /// <summary> /// 重寫OnException方法來捕獲異常數據 /// </summary> /// <param name="filterContext"></param> public override void OnException(ExceptionContext filterContext) { base.OnException(filterContext); //捕獲當前異常數據 var ex = filterContext.Exception; //將異常數據入隊 Exceptions.Enqueue(ex); //跳轉到錯誤頁面 filterContext.HttpContext.Response.Redirect("/Error.html"); } }}
Log4Net的配置是在應用程序配置文件中進行的,我們先在配置文件中進行Log4Net的配置。Log4Net需要配置的節點位置和SpringNet完全相同,首先需要在configSessions中新增子節點,然后在configuration節點中增加log4net節點完成具體配置。
新聞熱點
疑難解答
圖片精選