一切福田,不離方寸,從心而覓,感無不通。

ASP.NET Application_Error错误日志写入

一个web项目开发已完成,测试也通过,但是,bug是测不完的,特别是在一个大的网络环境下。那么,我们就应该记录这些错误,然后改正。这里,我的出错管理页面是在global.asax里面的,利用里面的Application_Error函数。

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; 
            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() + ".html";
                    path = Server.MapPath("~/ErrorLog/") + year + "/" + month;
                    //如果目录不存在则创建
                    if (!System.IO.Directory.Exists(path))
                    {
                        System.IO.Directory.CreateDirectory(path);
                    }
                    System.IO.FileInfo file = new System.IO.FileInfo(path + "/"+filename);        
                   
                    //文件不存在就创建,true表示追加
                    writer = new System.IO.StreamWriter(file.FullName, true);
                    string ip = "用户IP:" + Request.UserHostAddress;
                    string line = "—————————————————--";
                    string log = "<p style=’font-size:9pt;'><br>" + line + "<br><font color=red>" + errortime + "&nbsp;&nbsp;" + erroraddr + "</font><br><font color=green>" + "<br/>" + ip + errorinfo + "<br>" + errorsource + "<br>" + errortrace.Replace("\r\n", "<br>") + "</font></p>";
                    writer.WriteLine(log);         
                   }
            }
            finally 
            {
                if (writer != null)
                    writer.Close();
                    
            }    
            Response.Redirect("~/ErrorPage.aspx");
    }
    void Session_Start(object sender, EventArgs e) 
    {
        // 在新会话启动时运行的代码
    }
    void Session_End(object sender, EventArgs e) 
    {
        // 在会话结束时运行的代码。 
        // 注意: 只有在 Web.config 文件中的 sessionstate 模式设置为
        // InProc 时,才会引发 Session_End 事件。如果会话模式设置为 StateServer 
        // 或 SQLServer,则不会引发该事件。
    }
       
</script>
 
显示出错信息的页面 
ErrorPage.aspx代码: 
 
<%@ Page Language="C#" CodeFile="ErrorPage.aspx.cs" Inherits="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>
<script language="javascript" type="text/javascript">
// <!CDATA[
// ]]>
</script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <table width="600" border="0" align="center" cellpadding="1" cellspacing="0">
<tr>
<td  class="table_bgcolor" style="height: 138px">
<table width="100%" border="1" cellpadding="5" cellspacing="0" class="table_bordercolor">
<tr bgcolor="#e4e4e4">
<td class="table_title" style="height: 22px"><STRONG><FONT color="red">发生问题:</FONT></STRONG></td>
</tr>
<tr>
<td height="22">
<table cellSpacing="0" cellPadding="0" width="100%" border="0">
<tr>
<td height="22">
<asp:Label id="lblMsg" runat="server" Width="100%"></asp:Label>
</td>
</tr>
</table>
</td>
</tr>
<tr>
<td style="height: 22px">
<div align="center">
<asp:Button ID="Button1" Text="返 回" style="WIDTH: 100p" runat="server" OnClick="Button1_Click" />
</td>
</tr>
</table>
</td>
</tr>
</table>
    </div>
    </form>
</body>
</html>

ErrorPage.aspx.cs 

    protected void Page_Load(object sender, EventArgs e)
   {
       if (!Page.IsPostBack)
       {
           lblMsg.Text = Application["error"].ToString() + "<p>该信息已被系统记录,请稍候重试或与管理员联系。";
           Server.ClearError();
       }
   }
   protected void Button1_Click(object sender, EventArgs e)
   {
       Response.Redirect("~/Login.aspx");
   }

application_error是为了捕获那些未处理的异常,没有想到的异常

try…catch…还是需要的,为了精确定位错误的类型及信息,提出精确的提醒信息。

from:http://blog.sina.com.cn/s/blog_6edd5506010190yh.html