程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> ASP.NET >> ASP.NET基礎 >> ASP.NET記錄錯誤日志的實現方法

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

編輯:ASP.NET基礎

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

首先,我先寫一個靜態方法用於將錯誤信息記錄到文本文件,這裡是將錯誤信息記錄到服務器上的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文件,用於使用者出現錯誤時呈現的錯誤頁面。

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved