ASP.NET記錄錯誤日誌
阿新 • • 發佈:2018-11-03
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.IO; using System.Text; using Newtonsoft.Json.Linq; using Newtonsoft.Json; namespace ERPSite.UniversalLog { public class ExceptionLog { /// <summary> /// 寫入日誌到文字檔案 /// </summary> /// <param name="action">動作</param> /// <param name="e">異常</param> /// <param name="Pars">引數</param> /// <param name="Name">使用者名稱</param> public static void WriteTextLog(string action = "123",Exception e=null,string Pars="",string Name="") { DateTime time = DateTime.Now; string path = AppDomain.CurrentDomain.BaseDirectory + @"\Log\"; if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } string fileFullPath = path + time.ToString("yyyy-MM-dd") + ".txt"; StringBuilder str = new StringBuilder();<span style="font-family: Arial, Helvetica, sans-serif;">//要寫入的資訊</span> str.Append("【Time】: " + time.ToString() + "\r\n"); str.Append("【Action】: " + action + "\r\n"); str.Append("【Parameters】: " + Pars + "\r\n"); str.Append("【Message】: " + e.Message + "\r\n"); str.Append("【Source】:"+ e.Source + "\r\n"); str.Append("【StackTrace】: " + e.StackTrace + "\r\n"); str.Append("【操作人】: " + Name + "\r\n"); str.Append("============================================================\r\n\r\n"); try { using (FileStream fs = new FileStream(fileFullPath, !File.Exists(fileFullPath) == true ? FileMode.Create : FileMode.Append)) { using (StreamWriter sw = new StreamWriter(fs, Encoding.Default)) { //宣告資料流檔案寫入方法 sw.WriteLine(); sw.Write(str.ToString()); sw.Flush(); sw.Close(); sw.Dispose(); } } } catch { } } } }