只需要在Global.asax文件中添加以下代码,则可以在出错后友好的展示错误页,也不需要在很多地方写记录错误日志的代码
protected void Application_Error(object sender, EventArgs e) { if (HttpContext.Current.IsCustomErrorEnabled) { return; } var exception = Server.GetLastError(); var httpException = new HttpException(null, exception); //记录错误日志 if (httpException.InnerException != null) { LogManager.WriterLog(httpException.InnerException.ToString(), DateTime.Now.ToString("yyyyMMdd")); } var routeData = new RouteData(); routeData.Values.Add("controller", "Error"); routeData.Values.Add("action", "Index"); routeData.Values.Add("httpException", httpException); Server.ClearError(); var errorController = ControllerBuilder.Current.GetControllerFactory().CreateController( new RequestContext(new HttpContextWrapper(Context), routeData), "Error"); errorController.Execute(new RequestContext(new HttpContextWrapper(Context), routeData)); }
LogManager.WriterLog是我自己写的一个日志记录类,简单的记录了一下错误的内容
public class LogManager { /// <summary> /// 记录错误日志 /// </summary> /// <param name="content">错误内容</param> /// <param name="fileName">文件名称</param> public static void WriterLog(string content, string fileName) { var path = HttpRuntime.AppDomainAppPath + "\\Log\\" + DateTime.Now.ToString("yyyy-MM") + "\\"; if (!Directory.Exists(path)) { Directory.CreateDirectory(path); } fileName = path + fileName + ".txt"; if (!File.Exists(fileName)) { File.Create(fileName).Dispose(); } using (var sw = File.AppendText(fileName)) { sw.WriteLine(DateTime.Now); sw.WriteLine(content); sw.WriteLine(""); } } }
在发布到服务器的时候,我们可以同时把项目的.pdb文件也拷贝过去,这样记录错误日志的时候会把行号和错误文件所在的路径也记录下来,比较方便定位和修。
时间: 2024-10-24 19:49:46