前言:由于現在日志非常重要,但是在哪里打寫日志比較好呢,我選擇的是在global中,把錯誤代碼網上拋,而不是在底層寫大量的try catch然后在catch中來寫日志,每個catch中的寫日志這樣就會避免了很多重復代碼。當然這是目前我們采取的一個方法,大家可以提出更好地方法來管理日志,下面我開始寫代碼
第一步:盡量拋棄項目中try catch??聪麓a
PRivate void ExceptionTestOne() { int a = 1; int b = 0; int c = a/b; }
上面代碼會拋一個異常
第二步:如果項目中必須用try catch怎么辦,因為有時候連接wcf的時候如果出現異常時候我們需要關閉連接避免堵塞,那么我們就采取拋異常的方法
private void ExceptionTestTwo() { try { List<Simple> simples = null; simples.Add(new Simple() { Name = "發生異常" }); } catch (Exception ex) { throw new Exception("",ex); } }
第三步:我們新建一個global.asax 在application_Error中把異常信息加入隊列中 如下
//創建一個靜態的隊列記錄把異常都放在隊列中 private static Queue<Exception> queue = new Queue<Exception>(); protected void Application_Error(object sender, EventArgs e) { Exception exp = Server.GetLastError(); if (exp != null) { queue.Enqueue(exp); } Server.ClearError(); }
第四步:異常信息加入日志(這里為了簡單就寫入txt文本中了)
protected void Application_Start(object sender, EventArgs e) { ThreadPool.QueueUserWorkItem(a => { while (true) { try { if (queue.Count > 0) { Exception ex = queue.Dequeue(); WriteLog(ex); } else { System.Threading.Thread.Sleep(TimeSpan.FromSeconds(3)); } } catch (Exception ex) {
WriteLog(ex);
} } }); }
private void WriteLog(Exception ex) { if (!File.Exists(@"E:/C#系列/ExceptionDealWith/ExceptionDealWith/Log.txt")) { FileStream fs1 = new FileStream(@"E:/C#系列/ExceptionDealWith/ExceptionDealWith/Log.txt", FileMode.Create, Fileaccess.Write);//創建寫入文件 StreamWriter sw = new StreamWriter(fs1); sw.WriteLine(ex.Message);//開始寫入值 sw.Close(); fs1.Close(); } else { StreamWriter sr = File.AppendText(@"E:/C#系列/ExceptionDealWith/ExceptionDealWith/Log.txt"); sr.WriteLine(ex.Message); sr.Close(); } }
當然接入錯誤信息你可以多定義幾個比喻ip地址,堆棧信息錯誤等基本就是這么多了。這是基本思路。有日志了我就就可以根據時間,ip等進行查詢日志日志信息
下載
新聞熱點
疑難解答