利用Global.asax的Application_Error實(shí)現(xiàn)錯(cuò)誤記錄
錯(cuò)誤日志
復(fù)制代碼代碼如下:
void Application_Error(object sender, EventArgs e)
{
// 在出現(xiàn)未處理的錯(cuò)誤時(shí)運(yùn)行的代碼
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操作系統(tǒng):" + Request.Browser.Platform.ToString());
str.Append("\r\n.錯(cuò)誤信息:");
str.Append("\r\n\t頁(yè)面:" + Request.Url.ToString());
str.Append("\r\n\t錯(cuò)誤信息:" + ex.Message);
str.Append("\r\n\t錯(cuò)誤源:" + ex.Source);
str.Append("\r\n\t異常方法:" + ex.TargetSite);
str.Append("\r\n\t堆棧信息:" + ex.StackTrace);
str.Append("\r\n--------------------------------------------------------------------------------------------------");
//創(chuàng)建路徑
string upLoadPath = Server.MapPath("~/log/");
if (!System.IO.Directory.Exists(upLoadPath))
{
System.IO.Directory.CreateDirectory(upLoadPath);
}
//創(chuàng)建文件 寫入錯(cuò)誤
System.IO.File.AppendAllText(upLoadPath + DateTime.Now.ToString("yyyy.MM.dd") + ".log", str.ToString(), System.Text.Encoding.UTF8);
//處理完及時(shí)清理異常
Server.ClearError();
//跳轉(zhuǎn)至出錯(cuò)頁(yè)面
Response.Redirect("~/error.html");
}