.net C# web程式執行中錯誤日誌寫入文字檔案中
阿新 • • 發佈:2019-01-03
網上找的原始碼,自己根據實際情況進行了修改,能將日誌儲存在發不出來的web程式根目錄下的ErrorLog資料夾內。
#region 建立錯誤日誌
///-----------------------------------------------------------------------------
/// <summary>建立錯誤日誌 在c:\ErrorLog\</summary>
/// <param name="strFunctionName">strFunctionName,呼叫方法名</param>
/// <param name="strErrorNum">strErrorNum,錯誤號</param>
/// <param name="strErrorDescription">strErrorDescription,錯誤內容</param>
/// <returns></returns>
public static void ErrorLog(string strFunctionName, string strErrorNum, string strErrorDescription)
{
string strMatter; //錯誤內容
string strPath; //錯誤檔案的路徑
DateTime dt = DateTime.Now;
try
{
strPath = HttpContext.Current.Server.MapPath("\\ErrorLog"); //返回網站根目錄下查詢errolog資料夾地址
//strPath = "c:" + "\\ErrorLog";//暫時放在c:下
if (Directory.Exists(strPath) == false ) //工程目錄下 Log目錄 '目錄是否存在,為true則沒有此目錄
{
Directory.CreateDirectory(strPath); //建立目錄 Directory為目錄物件
}
strPath = strPath + "\\" + dt.ToString("yyyyMM");
if (Directory.Exists(strPath) == false) //目錄是否存在 '工程目錄下 Log\月 目錄 yyyymm
{
Directory.CreateDirectory(strPath); //建立目錄//日誌檔案,以 日 命名
}
strPath = strPath + "\\" + dt.ToString("yyyyMMdd") + ".txt";
strMatter = "方法名:"+strFunctionName + " , 錯誤程式碼:" + strErrorNum + " , " + strErrorDescription.Replace("\r","");//生成錯誤資訊
StreamWriter FileWriter = new StreamWriter(strPath, true); //建立日誌檔案
FileWriter.WriteLine("Time: " + dt.ToString("HH:mm:ss") + " Details: " + strMatter);
FileWriter.WriteLine("--------------------------------------------------------------------------------------------------");
FileWriter.Close(); //關閉StreamWriter物件
}
catch (Exception ex)
{
//("寫錯誤日誌時出現問題,請與管理員聯絡! 原錯誤:" + strMatter + "寫日誌錯誤:" + ex.Message.ToString());
string str = ex.Message.ToString();
}
}