您的位置:首页 > 编程语言 > ASP

asp.net 错误信息记录到日志文件

2012-10-17 11:06 726 查看
昨天正式给上司汇报工作,大部分还比较满意.说道错误信息的处理方式怎么处理时有没有做错误日志;没,那就参考公司的的错误日志类操作类吧.

在global.asax里面添加也是实现HttpApplication的application_error事件

View Code

void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs
// 在出现未处理的错误时运行的代码
string errorLog = Server.MapPath("~/App_Data/Error.log");
System.IO.FileStream fs = new System.IO.FileStream(errorLog, System.IO.FileMode.Append, System.IO.FileAccess.Write);
System.IO.StreamWriter sw = new System.IO.StreamWriter(fs);
Exception ex = Server.GetLastError();
string IP = "";//客户端IP
HttpRequest request = HttpContext.Current.Request;
string result = request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (null == result || result == String.Empty)
{
IP = request.ServerVariables["REMOTE_ADDR"];
}
else if (request.ServerVariables["HTTP_VIA"] != null)
{
IP = request.ServerVariables["HTTP_X_FORWARDED_FOR"].ToString().Split(',')[0].Trim();
}
else
{
IP = request.UserHostAddress;
}
if (ex.InnerException != null)
{
sw.WriteLine("IP:{0}\n时间:{1}\n错误消息:{2}\n位置:{3}\n地址:{4}\n\n", IP,DateTime.Now.ToString("yyyy年MM月dd日 HH:mm:ss ffff"), ex.ToString(), ex.InnerException, Request.Url.AbsolutePath);
}
else if (ex != null)
{
sw.WriteLine("IP:{0}\n时间:{1}\n错误消息:{2}\n地址:{3}\n\n", IP,DateTime.Now.ToString("yyyy年MM月dd日 HH:mm:ss ffff"), ex.ToString(), Request.Url.AbsolutePath);
}
else
{
sw.WriteLine("未知错误");
}
Server.ClearError();
sw.Close();
}


当然还要在app_data目录下新建一个error_log.txt文件
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐