![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
public class ErrorLog { /// <summary> /// 创建错误日志到文件 /// </summary> /// <param name="exceptionMessage">异常说明</param> /// <param name="exceptionStackTrace">异常跟踪堆栈信息</param> public static void AddLog(string exceptionMessage, string exceptionStackTrace) { string requestType = HttpContext.Current.Request.HttpMethod; string strUrl = HttpContext.Current.Request.Url.AbsolutePath; string strIP = HttpContext.Current.Request.UserHostAddress; string filePath = ConfigurationManager.AppSettings["ErrorLogPath"].ToString(); string serverPath = HttpContext.Current.Server.MapPath("~/" + filePath + ""); //创建日志目录 if (!Directory.Exists(serverPath)) { Directory.CreateDirectory(serverPath); } //指定日志文件目录 string filename = serverPath + "\\"+Convert.ToDateTime(DateTime.Now).ToShortDateString()+".txt"; if (File.Exists(filename)) { StreamWriter sw = File.AppendText(filename); sw.Write("访问时间:" + DateTime.Now.ToString() + " 访问IP:" + strIP + "\r\n"); sw.Write("请求方式:" + requestType + " 请求地址:" + strUrl + "\r\n"); sw.Write("异常说明:" + exceptionMessage + "\r\n"); sw.Write("跟踪信息:" + exceptionStackTrace + "\r\n"); sw.Write("----------------------------------------------------------------------------\r\n"); sw.Flush(); sw.Close(); } else { StreamWriter sw = File.CreateText(filename); sw.Write("访问时间:" + DateTime.Now.ToString() + " 访问IP:" + strIP + "\r\n"); sw.Write("请求方式:" + requestType + " 请求地址:" + strUrl + "\r\n"); sw.Write("异常说明:" + exceptionMessage + "\r\n"); sw.Write("跟踪信息:" + exceptionStackTrace + "\r\n"); sw.Write("----------------------------------------------------------------------------\r\n"); sw.Flush(); sw.Close(); } } public static void ShowError(string exceptionMessage, string exceptionStackTrace) { AddLog(exceptionMessage, exceptionStackTrace); string errorHandlerPage = "~/errorpage.aspx?msg=" + HttpContext.Current.Server.UrlEncode(exceptionMessage); if (!string.IsNullOrEmpty(errorHandlerPage)) { HttpContext.Current.Response.Redirect(errorHandlerPage); } } }
添加处理模块:
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
public class WebHttpModule : IHttpModule { #region IHttpModule 成员 public void Dispose() { } public void Init(HttpApplication context) { //context.Error += new EventHandler(context_Error); } void context_Error(object sender, EventArgs e) { Exception ex; ex = HttpContext.Current.Server.GetLastError(); string errrorMessage = ex == null ? string.Empty : ex.Message; string stackTrace = ex == null ? string.Empty : ex.StackTrace; //在这里将出错信息记录在文件日志中 ErrorLog.ShowError(errrorMessage, stackTrace); } #endregion }