C#將異常信息添加到日志


C#將程序拋出的異常信息添加到錯誤日志

錯誤日志是軟件用來記錄運行時出錯信息的文本文件。編程人員和維護人員等可以利用錯誤日志對系統進行調試和維護。

為程序添加錯誤日志的好處是當程序有運行錯誤時,根據錯誤日志我們可以快速定位到錯誤,排查原因、解決問題,這是對於運行在線上而不能調試的網站的一個非常有必要的功能。

 1 using System;
 2 using System.IO;
 3 using System.Text;
 4 
 5 namespace TestService
 6 {
 7     public class ErrorLog
 8     {
 9         public static void ErrorLogTxt(Exception ex)
10         {
11             //獲取文件路徑(相對於程序的基目錄路徑)
12             string FilePath = AppDomain.CurrentDomain.BaseDirectory + "/File/ErrorLog.txt";
13 
14             StringBuilder msg = new StringBuilder();
15             msg.Append("*************************************** \r\n");
16             msg.AppendFormat(" 異常發生時間: {0} \r\n", DateTime.Now);
17             msg.AppendFormat(" 異常類型: {0} \r\n", ex.HResult);
18             msg.AppendFormat(" 導致當前異常的 Exception 實例: {0} \r\n", ex.InnerException);
19             msg.AppendFormat(" 導致異常的應用程序或對象的名稱: {0} \r\n", ex.Source);
20             msg.AppendFormat(" 引發異常的方法: {0} \r\n", ex.TargetSite);
21             msg.AppendFormat(" 異常堆棧信息: {0} \r\n", ex.StackTrace);
22             msg.AppendFormat(" 異常消息: {0} \r\n", ex.Message);
23             msg.Append("***************************************");
24 
25             try
26             {
27                 if (File.Exists(FilePath))//如果文件存在
28                 {
29                     //寫異常信息寫入文件
30                     using (StreamWriter tw = File.AppendText(FilePath))
31                     {
32                         tw.WriteLine(msg.ToString());
33                     }
34                 }
35                 else
36                 {
37                     //如果文件不存在則創建后將異常信息寫入
38                     TextWriter tw = new StreamWriter(FilePath);
39                     tw.WriteLine(msg.ToString());
40                     tw.Flush();//將緩沖區的數據強制輸出,清空緩沖區
41                     tw.Close();//關閉數據流
42                     tw = null;
43                 }
44             }
45             catch (Exception exx)
46             {
47                 Console.ReadKey();
48             }
49 
50         }
51     }
52 }

在使用 TextWrite 對象時,在最后一定要記得手動關閉,否則會造成意想不到的錯誤,特別是內存泄露。

使用異常日志記錄方法 ,在程序可能出現異常的地方用 try ... catch 塊來包裝,在 catch 塊中調用這個異常的方法,將異常日志記錄下來

 1 public LoginResult RegistSend(MainInfoResult model, string uver)
 2 {
 3    try
 4    {
 5       Sends(model.UEmail, "注冊賬號", uver);
 6       result.Status = ResultStatus.Success;
 7       result.Message = "驗證碼已發送至您的郵箱!";
 8    }
 9    catch (Exception ex)
10    {
11       ErrorLog.ErrorLogTxt(ex);//調用錯誤日志類
12       result.Status = ResultStatus.Fail;
13       result.Message = ex.Message;
14    }
15    return result;
16 }

日志記錄效果:

End!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM