在开发程序中,错误日志很有必要.今天就把使用到的添加错误日志,记录下来,方便以后查看
利用的 asp.net 错误处理机制
Application_Error
贴出代码
protected void Application_Error(object sender, EventArgs e)
{
c: Exception Lasterr = Server.GetLastError().GetBaseException();//利用内部服务器对象的GetLastError方法,该方法是返回一个异常,
try
{
string path = "/Error/" + DateTime.Today.ToString("yyMMdd") + ".txt";
string mapPath = HttpContext.Current.Server.MapPath(path);//利用服务端的mapPath方法,指定虚拟路径相对应的物理路径
//如果路径下面文件不存在
if (!File.Exists(mapPath))
{
File.Create(mapPath).Close();//在该文件夹下面创建文件,并且关闭流,用于释放
}
//实力文件流用于写入
using (StreamWriter writer =File.AppendText(mapPath))//使用apperntext追加到文件中
{
writer.WriteLine("{0}", DateTime.Now.ToString());
writer.WriteLine(Lasterr.Message.ToString());
writer.WriteLine("-------------------------------");
writer.Flush();//清理缓冲区,并使数据插入
writer.Close();//写入之后关闭
}
}
catch(Exception ex)
{
goto c;
}
来源: http://www.bubuko.com/infodetail-2455663.html