C# 記錄錯誤日志(簡介,方法代碼)
簡介:程序在出錯時記錄錯誤日志,可以有利於維護,也可以記錄一些程序內部運行的操作等等,它的作用很大,也很重要
方法1:
1 /// <summary> 2 /// 將異常打印到LOG文件 3 /// </summary> 4 /// <param name="ex">異常</param> 5 /// <param name="LogAddress">日志文件地址</param> 6 public static void WriteLog(Exception ex, string LogAddress) 7 { 8 //如果日志文件路徑LogAddress為空,則默認在Debug目錄下新建 YYYY-mm-dd-Log.log文件 9 if (LogAddress == "") 10 { 11 LogAddress = Environment.CurrentDirectory + '\\' + 12 DateTime.Now.Year + '-' + 13 DateTime.Now.Month + '-' + 14 DateTime.Now.Day + "-Log.log"; 15 } 16 //把異常信息輸出到文件 17 StreamWriter fs = new StreamWriter(LogAddress, true); 18 fs.WriteLine("當前時間:" + DateTime.Now.ToString()); 19 fs.WriteLine("異常信息:" + ex.Message); 20 fs.WriteLine("異常對象:" + ex.Source); 21 fs.WriteLine("調用堆棧:\n" + ex.StackTrace.Trim()); 22 fs.WriteLine("觸發方法:" + ex.TargetSite); 23 fs.WriteLine(); 24 fs.Close(); 25 }
