C#错误异常日志记录到文件
当我们将网站布署到线上之后,为了实时了解网站的运行情况,如是否有错误页面、网站运行速度、是否有攻击等。那么我们就很有必要为网站加上错误与异常记录到日志文件,这样就可以随时查看网站的线上运行情况,另有一个好处是当网站有运行错误页面时,根据错误日志我们可以快速到定位到错误行进行排查原因、解决问题,这个是对于运行在线上而不能调试的网站的一个非常有必要的功能。
具体实现方法:
在全局文件Global.asax.cs中添加Application_Error的方法。只要当程序有错误时程序就会自动执行该方法,从而记录到错误日志。
void Application_Error(object sender, EventArgs e) { //在出现未处理的错误时运行的代码 Exception ex = Server.GetLastError().GetBaseException(); string errorTime = "异常时间:" + DateTime.Now.ToString(); string errorAddress = "异常地址:" + Request.Url.ToString(); string errorInfo = "异常信息:" + ex.Message; string errorSource = "错误源:" + ex.Source; string errorType = "运行类型:" + ex.GetType(); string errorFunction = "异常函数:" + ex.TargetSite; string errorTrace = "堆栈信息:" + ex.StackTrace; Server.ClearError(); System.IO.StreamWriter writer = null; try { lock (this) { //写入日志 string path = string.Empty; path = Server.MapPath("~/ErrorLogs/"); //不存在则创建错误日志文件夹 if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } path +=string.Format(@"\{0}.txt", DateTime.Now.ToString("yyyy-MM-dd")); writer = !File.Exists(path) ? File.CreateText(path) : File.AppendText(path); //判断文件是否存在,如果不存在则创建,存在则添加 writer.WriteLine("用户IP:" + Request.UserHostAddress); writer.WriteLine(errorTime); writer.WriteLine(errorAddress); writer.WriteLine(errorInfo); writer.WriteLine(errorSource); writer.WriteLine(errorType); writer.WriteLine(errorFunction); writer.WriteLine(errorTrace); writer.WriteLine("********************************************************************************************"); } } finally { if (writer != null) { writer.Close(); } } Server.Transfer("~/500webpage.aspx"); //跳转到显示友好错误的页面 }
GarsonZhang www.yesdotnet.com
版权声明:本文为YES开发框架网发布内容,转载请附上原文出处连接
post YES开发框架