ASP.net 错误处理
网站需要长期的维护和大量人工的测试,所以记录网站出现的错误是一个比较好的功能.可以很好找到出错的代码.
记录的越加详细,越容易找到问 题 ,下面是我写的代码
void Application_Error(object sender, EventArgs e)
{
//在出现未处理的错误时运行的代码
Exception objErr = Server.GetLastError().GetBaseException();
string error = "<p>发生异常页面:" + Request.Url.ToString() + "</p>";
string error1 = "<p>异常信息提示:" + objErr.Message + "</p>";
// CreateSqlLog(error, error1);//只是记录文件错误信息,并没有做对应的处理
string error2 = "<p>导致异常的来源:堆栈信息:" + objErr.StackTrace +" 错误源:"+objErr .Source+" 异常的方法:"+objErr .TargetSite +"</p>";
CreateSqlLog(error, error1, error2);
}
static void CreateSqlLog(string Description, string Content,string Source)
{
//lock (ctx)
//{
// CreateSqlLog(Description, Content);
//}
string FilePath="";
string strTmp = "";
FilePath = System.Web.HttpContext.Current.Server.MapPath("~/");//程序的要目录,类似一个绝对路径
strTmp = "ErrorLog\\"+DateTime.Now.Year.ToString()+"\\"+DateTime .Now .Month.ToString ()+"\\";//以年份创建文件夹
FilePath += strTmp;
if (!System.IO.Directory.Exists(FilePath))
{
System.IO.Directory.CreateDirectory(FilePath);
}// 文件夹操作完成。
//记录文件按月算
FilePath += DateTime.Now .Date .ToString ("dd")+".txt";
//路径上文件存在就附加文字,不存在就创建,添加文字
System.IO.StreamWriter sw = new System.IO.StreamWriter(FilePath , true, System.Text.Encoding.Default);
sw.WriteLine("[system time]: " + DateTime.Now.ToString() + " [User IP]:" + getIP());
sw.WriteLine("---------------------------------------------------------------------------------------");
sw.WriteLine(Description.ToString() + ":" + Content.ToString());
sw.WriteLine();
sw.WriteLine("[Source]:" + Source);
sw.WriteLine();
sw.Close();
}
private static string getIP()
{
string result = HttpContext.Current.Request.UserHostAddress;
if (string.IsNullOrEmpty(result))
{
result = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
}
if (string.IsNullOrEmpty(result))
{
result = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
}
if (string.IsNullOrEmpty(result))
{
return "127.0.0.1";
}
return result;
}
好的,我的问题来了.
我现在想知道,出错页面的来源在那,如:是自己手输入的地址,还是点击的,若是点击的 点击的页面是那.
等等 类似的 总之一个要求,让错误提示 更加详细起来 ,感谢大家提供.