Asp.Net MVC中记录错误日志保存到本地txt文件
为了方便查询系统出错弄个错误日志出来对于维护运维来说是很有必要的。
1、开始
在Asp.Net MVC项目中的App_Start添加一个用于处理异常类的文件ErrorLog让他继承HandleErrorAttribute类并重写OnException方法
public class ErrorLog: HandleErrorAttribute { public override void OnException(ExceptionContext filterContext) { if(!filterContext.ExceptionHandled) { //当前Controller名称 string controllName = (string)filterContext.RouteData.Values["controller"]; //当前Action string actionName = (string)filterContext.RouteData.Values["action"]; //定义一个HandErrorInfo,用于Error视图展示异常信息 HandleErrorInfo model = new HandleErrorInfo(filterContext.Exception, controllName, actionName); //时间用来给txt命名 string thisTime = DateTime.Now.ToString("yyyyMMdd"); string errorDetails = $"出错时间:{DateTime.Now.ToString()},错误发生在{model.ControllerName}控制器的{model.ActionName},错误类型:{model.Exception.Message}"; string splitLine = "============================下一条=============================="; //日志存放位置,在项目目录里面一个月一个文件夹,一天一个文件 string path = HttpContext.Current.Server.MapPath(@"\ErrorLog\" + DateTime.Now.Year.ToString()+ @"\" + DateTime.Now.ToString("MM") + @"\" ); //判断文件夹不存在就创建 if (!Directory.Exists(path)) Directory.CreateDirectory(path); //写入日志 using (System.IO.StreamWriter file = new System.IO.StreamWriter(path + thisTime+".txt", true)) { file.WriteLine(errorDetails); file.WriteLine(model.Exception.StackTrace); file.WriteLine(splitLine); } //出错跳转到指定页面,如果Global.asax写了Application_Error方法可以不用写 ViewResult result = new ViewResult { ViewName = this.View,//设置异常时跳转的404页面 ViewData = new ViewDataDictionary<HandleErrorInfo>(model) //定义ViewData,泛型 }; filterContext.Result = result; filterContext.ExceptionHandled = true;//设置异常已处理 } } }
在视图里面的shared文件夹下面加一个Error视图,里面就是错误日志,类似于404页面一样的功能
2、配置App_Start
在App_Start文件夹下面的FilterConfig.cs文件里面配置
public class FilterConfig { public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new ErrorLog() { View="Error"}); } }
ErrorLog别写错了,里面有个原始的HandleErrorAttribute类改名为你第一步添加的类
3、最后看一下Gloabl.asax
看看里面注册了FilterConfig没有,一般都是有的
public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters); RouteConfig.RegisterRoutes(RouteTable.Routes); BundleConfig.RegisterBundles(BundleTable.Bundles); } }
4、调用实例
我写的一个图片上传,没有文件夹抛异常
/// <summary> /// 图片上传 /// </summary> /// <param name="file">图片</param> /// <returns></returns> public ActionResult FileUpLoad1(HttpPostedFileBase file) { var ret = string.Empty; try { string fileName = Guid.NewGuid()+file.FileName; string filePath = Server.MapPath(@"\FileUp2\"); //if (!Directory.Exists(filePath)) // Directory.CreateDirectory(filePath); file.SaveAs(Path.Combine(filePath, fileName)); } catch (Exception ex) { ret = ex.Message + ":" + ex.InnerException; throw new Exception (ex.Message + ":" + ex.InnerException); } if(string.IsNullOrEmpty(ret)) return Json(new { code = "0", msg = "文件上传成功!", data = "" }); else return Json(new { code = "1", msg = "文件上传失败!", data = ret }); }
注意要想记录日志一定要把异常抛出来 就是 throw new Exception (ex.Message + ":" + ex.InnerException);
5、效果
版权声明:本文为 魏杨杨 原创文章并发布到博客园, 除了【萬仟网】外, 其他平台欢迎转载,但必须在文章页面明显位置写明作者和出处,非常感谢。技术交流QQ群 99210270
微信扫一扫关注我公众号
一起学习,一起进步
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?