.Net Mvc過濾器觀察者模式記錄網站報錯資訊
阿新 • • 發佈:2019-08-18
基本介紹:
觀察者模式是一種物件行為模式。它定義物件間的一種一對多的依賴關係,當一個物件的狀態發生改變時,所有依賴於它的物件都得到通知並被自動更新。在觀察者模式中,主題是通知的釋出者,它發出通知時並不需要知道誰是它的觀察者,可以有任意數目的觀察者訂閱並接收通知。觀察者模式不僅被廣泛應用於軟體介面元素之間的互動,在業務物件之間的互動、許可權管理等方面也有廣泛的應用。
第一步:自定義過濾器錯誤類(MyExceptionFilterAttribute.cs)
1 using Sam.OA.Common; 2 using System.Web.Mvc; 3 4 namespace Sam.OA.WEBAPP.Models 5 { 6 public class MyExceptionFilterAttribute: HandleErrorAttribute 7 { 8 public override void OnException(ExceptionContext filterContext) 9 { 10 base.OnException(filterContext); 11 LogHelper.WriteLog(filterContext.Exception.ToString()); 12 } 13 } 14 }
第二步:改造RegisterGlobalFilters.cs
1 using Sam.OA.WEBAPP.Models; 2 using System.Web.Mvc; 3 4 namespace Sam.OA.WEBAPP 5 { 6 public class FilterConfig 7 { 8 public static void RegisterGlobalFilters(GlobalFilterCollection filters) 9 { 10 //filters.Add(new HandleErrorAttribute()); 11 filters.Add(new MyExceptionFilterAttribute()); //新增自定義錯誤類 12 } 13 } 14 }
第三步:觀察者模式實現操作日誌
日誌介面(ILogWrite.cs)
1 namespace Sam.OA.Common 2 { 3 /// <summary> 4 /// 日誌檔案介面 5 /// </summary> 6 public interface ILogWrite 7 { 8 void WriteLogInfo(string txt); 9 } 10 }
記錄檔案中(TextFileWriter.cs)
1 namespace Sam.OA.Common 2 { 3 public class TextFileWriter : ILogWrite 4 { 5 /// <summary> 6 /// 將錯誤資訊記錄到檔案中 7 /// </summary> 8 /// <param name="txt"></param> 9 public void WriteLogInfo(string txt) 10 { 11 //具體實現方法略。。。。 12 } 13 } 14 }
記錄SqlServer中(SqlServerWriter.cs)
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 namespace Sam.OA.Common 8 { 9 public class SqlServerWriter : ILogWrite 10 { 11 /// <summary> 12 /// 記錄SqlServer資料庫中 13 /// </summary> 14 /// <param name="txt"></param> 15 public void WriteLogInfo(string txt) 16 { 17 //具體實現方式略。。。。 18 } 19 } 20 }
日誌檔案幫助類(LogHelper.cs)
1 using System; 2 using System.Collections.Generic; 3 using System.Threading; 4 5 namespace Sam.OA.Common 6 { 7 public class LogHelper 8 { 9 public static Queue<string> ExceptionStringQueue = new Queue<string>(); 10 public static List<ILogWrite> LogWriteList = new List<ILogWrite>(); 11 static LogHelper() 12 { 13 LogWriteList.Add(new TextFileWriter()); 14 LogWriteList.Add(new SqlServerWriter()); 15 ThreadPool.QueueUserWorkItem(obj => 16 { 17 lock (ExceptionStringQueue) 18 { 19 string str = ExceptionStringQueue.Dequeue(); 20 foreach (var logWrite in LogWriteList) 21 { 22 logWrite.WriteLogInfo(str); 23 } 24 } 25 }); 26 } 27 public static void WriteLog(string exceptionText) 28 { 29 try 30 { 31 lock (ExceptionStringQueue) 32 { 33 ExceptionStringQueue.Enqueue(exceptionText); 34 } 35 } 36 catch (Exception ex) 37 { 38 throw ex; 39 } 40 } 41 } 42 }
&n