1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > C#错误异常日志记录到文件

C#错误异常日志记录到文件

时间:2022-07-23 19:02:04

相关推荐

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"); //跳转到显示友好错误的页面 }

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。