最近做了一個小程序,要求在控制台中記錄程序運行的異常並輸出到指定的文件夾中,以下是我的具體的程序代碼:
public static void ErrorLog(Exception ex)
{
string FilePath = "/ErrorLog.txt";
StringBuilder msg = new StringBuilder ();
msg.Append("*************************************** \n");
msg.AppendFormat(" 異常發生時間: {0} \n",DateTime.Now);
msg.AppendFormat(" 異常類型: {0} \n",ex.HResult);
msg.AppendFormat(" 導致當前異常的 Exception 實例: {0} \n",ex.InnerException);
msg.AppendFormat(" 導致異常的應用程序或對象的名稱: {0} \n",ex.Source);
msg.AppendFormat(" 引發異常的方法: {0} \n",ex.TargetSite);
msg.AppendFormat(" 異常堆棧信息: {0} \n",ex.StackTrace);
msg.AppendFormat(" 異常消息: {0} \n",ex.Message);
msg.Append("***************************************");
try
{
if (File.Exists(FilePath))
{
using (StreamWriter tw = File.AppendText(FilePath))
{
tw.WriteLine(msg.ToString());
}
}
else
{
TextWriter tw = new StreamWriter(FilePath);
tw.WriteLine(msg.ToString());
tw.Flush();
tw.Close();
tw = null;
}
}
catch (Exception)
{
Console.ReadKey();
}
}
使用這個異常日志記錄方法 ,在程序可能出現異常的地方用 try ... catch 塊來包裝, 並在 catch 塊中 調用這個異常的方法,將異常日志記錄下來, 在使用 TextWrite 對象時,在最后一定要記得手動關閉, 否則會造成意想不到的錯誤,特別是內存泄露。
異常記錄的效果如下:

