asp.net錯誤記錄檔寫入

來源:互聯網
上載者:User

當我們一個web項目開發已完成,測試也通過了後,就把他放到網上去,但是,bug是測不完的,特別是在一個大的網路環境下。那麼,我們就應該記錄這些錯誤,然後改正。這裡,我的出錯管理頁面是在global.asax裡面的,因為裡面有一個Application_Error函數,我覺得這個就是管理錯誤的。其實,asp.net裡還有一個方法,就是在 page 裡指定出錯的頁面,由這個頁面專門管理,我覺得這個方法也好,但是每次都要到相應的page裡指定參數,不過,我覺得應該可以在web.config裡配置吧。但是我還是喜歡下面的方法。下面我們就開始吧。
Global.asax代碼:
<%@ Application Language="C#" %>

<script runat="server">

    void Application_Start(object sender, EventArgs e)
    {
        // 在應用程式啟動時啟動並執行代碼

    }
   
    void Application_End(object sender, EventArgs e)
    {
        //  在應用程式關閉時啟動並執行代碼

    }
       
    void Application_Error(object sender, EventArgs e)
    {
        // 在出現未處理的錯誤時啟動並執行代碼
       
            Exception objErr = Server.GetLastError().GetBaseException();
            string error = string.Empty;
            string errortime = string.Empty;
            string erroraddr = string.Empty;
            string errorinfo = string.Empty;
            string errorsource = string.Empty;
            string errortrace = string.Empty;

            error += "發生時間:" + System.DateTime.Now.ToString() + "<br>";
            errortime = "發生時間:" + System.DateTime.Now.ToString();

            error += "發生異常頁: " + Request.Url.ToString() + "<br>";
            erroraddr = "發生異常頁: " + Request.Url.ToString();

            error += "異常資訊: " + objErr.Message + "<br>";
            errorinfo = "異常資訊: " + objErr.Message;

            //error +="錯誤源:"+objErr.Source+"<br>";
            //error += "堆棧資訊:" + objErr.StackTrace + "<br>";
            errorsource = "錯誤源:" + objErr.Source;
            errortrace = "堆棧資訊:" + objErr.StackTrace;
            error += "--------------------------------------<br>";
            Server.ClearError();
            Application["error"] = error;

            //獨佔方式,因為檔案只能由一個進程寫入.
           System.IO.StreamWriter writer=null;
            try
            {              
                lock (this)
                {
                    // 寫入日誌
                    string year = DateTime.Now.Year.ToString();
                    string month = DateTime.Now.Month.ToString();
                    string path = string.Empty;
                    string filename = DateTime.Now.Day.ToString() + ".txt";
                    path = Server.MapPath("~/Error/") + year + "/" + month;
                    //如果目錄不存在則建立
                    if (!System.IO.Directory.Exists(path))
                    {
                        System.IO.Directory.CreateDirectory(path);
                    }
                    System.IO.FileInfo file = new System.IO.FileInfo(path + "/" + filename);
                    //if (!file.Exists)
                    //    file.Create();
                    //file.Open(System.IO.FileMode.Append);       
                    writer = new System.IO.StreamWriter(file.FullName, true);//檔案不存在就建立,true表示追加
                    writer.WriteLine("使用者IP:" + Request.UserHostAddress);
                    //if (Session["UserName"] != null)
                    //{
                    //    writer.WriteLine("使用者名稱" + System.Web.HttpContext.Current.Session["UserName"].ToString());
                    //}
                    writer.WriteLine(errortime);
                    writer.WriteLine(erroraddr);
                    writer.WriteLine(errorinfo);
                    writer.WriteLine(errorsource);
                    writer.WriteLine(errortrace);
                    writer.WriteLine("--------------------------------------------------------------------------------------");
                    //writer.Close();
                }
            }
            finally
            {
                if (writer != null)
                    writer.Close();
                   
            }   
            Response.Redirect("~/Error/ErrorPage.aspx");

    }

    void Session_Start(object sender, EventArgs e)
    {
        // 在新會話啟動時啟動並執行代碼
        Session.Timeout = 60;       
        if (Session.IsNewSession)
        {
            lock (this)
            {
                if (Application["Counts"] != null)
                {
                    Application["Counts"] = Int32.Parse(Application["Counts"].ToString()) + 1;
                }
                else
                {
                    Application["Counts"] = 1;
                }
            }
        }
    }

    void Session_End(object sender, EventArgs e)
    {
        // 在會話結束時啟動並執行代碼。
        // 注意: 只有在 Web.config 檔案中的 sessionstate 模式設定為
        // InProc 時,才會引發 Session_End 事件。如果會話模式設定為 StateServer
        // 或 SQLServer,則不會引發該事件。
        if (Application["Counts"] != null)
        {
            Application["Counts"] = Int32.Parse(Application["Counts"].ToString())-1;
        }       
    }
      
</script>

顯示出錯資訊的頁面
ErrorPage.aspx代碼:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ErrorPage.aspx.cs" Inherits="Error_ErrorPage" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>出錯資訊</title>
    <link href="css/SITE.CSS" type="text/css" rel="stylesheet" />  
</head>
<body>
    <form id="form1" runat="server">
        <asp:Label ID="Label1" runat="server" Width="568px"></asp:Label>
   
    </form>
</body>
</html>

ErrorPage.aspx.cs
 protected void Page_Load(object sender, EventArgs e)
    {
        this.Label1.Text = Application["Error"].ToString();
    }

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.