在ASP.NET中记录错误日志(使用Global.asax)
在Global.asax的Application_Error中的代码如下:
1
void Application_Error(object sender, EventArgs e) 2

{ 3
// 在出现未处理的错误时运行的代码4
Exception objErr = Server.GetLastError().GetBaseException();5
string error = string.Empty;6
string errortime = string.Empty;7
string erroraddr = string.Empty;8
string errorinfo = string.Empty;9
string errorsource = string.Empty;10
string errortrace = string.Empty;11

12
error += "发生时间:" + System.DateTime.Now.ToString() + "<br>";13
errortime = "发生时间:" + System.DateTime.Now.ToString();14

15
error += "发生异常页: " + Request.Url.ToString() + "<br>";16
erroraddr = "发生异常页: " + Request.Url.ToString();17

18
error += "异常信息: " + objErr.Message + "<br>";19
errorinfo = "异常信息: " + objErr.Message;20

21
//error +="错误源:"+objErr.Source+"<br>";22
//error += "堆栈信息:" + objErr.StackTrace + "<br>";23
errorsource = "错误源:" + objErr.Source;24
errortrace = "堆栈信息:" + objErr.StackTrace;25
error += "--------------------------------------<br>";26
Server.ClearError();27
Application["error"] = error;28
//独占方式,因为文件只能由一个进程写入.29
System.IO.StreamWriter writer = null;30
try31

{32
lock (this)33

{34
// 写入日志35
string year = DateTime.Now.Year.ToString();36
string month = DateTime.Now.Month.ToString();37
string path = string.Empty;38
string filename = DateTime.Now.Day.ToString() + ".txt";39
path = Server.MapPath("~/Error/") + year + "/" + month;40
//如果目录不存在则创建41
if (!System.IO.Directory.Exists(path))42

{43
System.IO.Directory.CreateDirectory(path);44
}45
System.IO.FileInfo file = new System.IO.FileInfo(path + "/" + filename);46
//if (!file.Exists)47
// file.Create();48
//file.Open(System.IO.FileMode.Append); 49
writer = new System.IO.StreamWriter(file.FullName, true);//文件不存在就创建,true表示追加50
writer.WriteLine("用户IP:" + Request.UserHostAddress);51
//if (Session["UserName"] != null)52
//{53
// writer.WriteLine("用户名" + System.Web.HttpContext.Current.Session["UserName"].ToString());54
//}55
writer.WriteLine(errortime);56
writer.WriteLine(erroraddr);57
writer.WriteLine(errorinfo);58
writer.WriteLine(errorsource);59
writer.WriteLine(errortrace);60
writer.WriteLine("--------------------------------------------------------------------------------------");61
//writer.Close();62
}63
}64
finally65

{66
if (writer != null)67
writer.Close();68

69
}70
Response.Redirect("~/Error/ErrorPage.aspx");71

72
}73

74
75


浙公网安备 33010602011771号