在做WEB开发时,经常会有一些常见的错误,上传文件不全,上传的数据不全,相关文件路径不正确...
今天应该GLOAD.ASAX文件做一个错误日志的小功能
代码如下
protected 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);//只是记录文件错误信息,并没有做对应的处理
// Server.ClearError();
//Application["error"] = error;
//Response.Redirect("~/ErrorPage.aspx");
}
public static void CreateSqlLog(string Description, string Content)
{
//lock (ctx)
//{
// CreateSqlLog(Description, Content);
//}
string FilePath="";
string strTmp = "";
FilePath = System.Web.HttpContext.Current.Server.MapPath("~/");//程序的要目录,类似一个绝对路径
strTmp = "ErrorLog//"+DateTime.Now.Year.ToString()+"//";以年份创建文件夹
FilePath += strTmp;
if (!Directory.Exists(FilePath))
{
Directory.CreateDirectory(FilePath);
}// 文件夹操作完成。
FilePath += "AttLog";
//记录文件按月算
FilePath += DateTime.Now.Year.ToString ()+DateTime .Now .Month.ToString ()+ ".txt";
//路径上文件存在就附加文字,不存在就创建,添加文字
StreamWriter sw = new StreamWriter(FilePath , true, System.Text.Encoding.Default);
sw.WriteLine("[system time]: " + DateTime.Now.ToString());
sw.WriteLine("---------------------------------------------------------------------------------------");
sw.WriteLine(Description.ToString() + ":" + Content.ToString());
sw.WriteLine();
sw.Close();
}
内容大概是这样的
<p>发生异常页面:http://localhost:5114/ErrorLog/2009/AttLog20012.txt</p>:<p>异常信息提示:文件不存在。</p>