利用Global.asax的Application_Error實現錯誤記錄
錯誤日志
復制代碼 代碼如下:
void Application_Error(object sender, EventArgs e)
{
// 在出現未處理的錯誤時運行的代碼
Exception ex = Server.GetLastError().GetBaseException();
StringBuilder str = new StringBuilder();
str.Append("\r\n" + DateTime.Now.ToString("yyyy.MM.dd HH:mm:ss"));
str.Append("\r\n.客戶信息:");
string ip = "";
if (Request.ServerVariables.Get("HTTP_X_FORWARDED_FOR") != null)
{
ip = Request.ServerVariables.Get("HTTP_X_FORWARDED_FOR").ToString().Trim();
}
else
{
ip = Request.ServerVariables.Get("Remote_Addr").ToString().Trim();
}
str.Append("\r\n\tIp:" + ip);
str.Append("\r\n\t浏覽器:" + Request.Browser.Browser.ToString());
str.Append("\r\n\t浏覽器版本:" + Request.Browser.MajorVersion.ToString());
str.Append("\r\n\t操作系統:" + Request.Browser.Platform.ToString());
str.Append("\r\n.錯誤信息:");
str.Append("\r\n\t頁面:" + Request.Url.ToString());
str.Append("\r\n\t錯誤信息:" + ex.Message);
str.Append("\r\n\t錯誤源:" + ex.Source);
str.Append("\r\n\t異常方法:" + ex.TargetSite);
str.Append("\r\n\t堆棧信息:" + ex.StackTrace);
str.Append("\r\n--------------------------------------------------------------------------------------------------");
//創建路徑
string upLoadPath = Server.MapPath("~/log/");
if (!System.IO.Directory.Exists(upLoadPath))
{
System.IO.Directory.CreateDirectory(upLoadPath);
}
//創建文件 寫入錯誤
System.IO.File.AppendAllText(upLoadPath + DateTime.Now.ToString("yyyy.MM.dd") + ".log", str.ToString(), System.Text.Encoding.UTF8);
//處理完及時清理異常
Server.ClearError();
//跳轉至出錯頁面
Response.Redirect("~/error.html");
}