ASP.NET記錄錯誤記錄檔的實現方法

來源:互聯網
上載者:User

在本文中,我們將通過一個簡單的處理來記錄在我們的網站中的錯誤和異常。我們這樣操作,每當遇到程式錯誤時,將使用者導航到一個單獨的頁面,同時錯誤將被記錄到伺服器上的一個文字檔,每當錯誤發生時,我們將以日誌的形式每天記錄。

首先,我先寫一個靜態方法用於將錯誤資訊記錄到文字檔,這裡是將錯誤資訊記錄到伺服器上的Error檔案夾下
代碼如下:

複製代碼 代碼如下:using System.Globalization;

/// <summary>
/// 用於將錯誤資訊輸出到txt檔案
/// </summary>
/// <param name="errorMessage">錯誤詳細資料</param>
public static void WriteError(string errorMessage)
{
try
{
string path = "~/Error/" + DateTime.Today.ToString("yyMMdd") + ".txt";
if (!File.Exists(System.Web.HttpContext.Current.Server.MapPath(path)))
{
File.Create(System.Web.HttpContext.Current.Server.MapPath(path)).Close();
}
using (StreamWriter w = File.AppendText(System.Web.HttpContext.Current.Server.MapPath(path)))
{
w.WriteLine("\r\nLog Entry : ");
w.WriteLine("{0}", DateTime.Now.ToString(CultureInfo.InvariantCulture));
w.WriteLine(errorMessage);
w.WriteLine("________________________________________________________");
w.Flush();
w.Close();
}
}
catch (Exception ex)
{
WriteError(ex.Message);
}
}

在網站Global.asax檔案的Application_Error中加入如下代碼複製代碼 代碼如下:void Application_Error(object sender, EventArgs e)
{
// 在出現未處理的錯誤時啟動並執行代碼
Exception objErr = Server.GetLastError().GetBaseException();
//記錄出現錯誤的IP地址
string strIP = Request.UserHostAddress;
string err = "Ip【" + strIP + "】" + Environment.NewLine + "Error in【" + Request.Url.ToString() +
"】" + Environment.NewLine + "Error Message【" + objErr.Message.ToString() + "】";
//記錄錯誤
FN.WriteError(err);
}

配置Web.Config檔案複製代碼 代碼如下:<system.web>
<customErrors mode="RemoteOnly" defaultRedirect="GenericErrorPage.htm">
<!--可以指定其他錯誤頁面...-->
</customErrors>
</system.web>

建立一個GenericErrorPage.htm檔案,用於使用者出現錯誤時呈現的錯誤頁面。

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.