Asp.Net MVC中记录错误日志保存到本地txt文件

本文介绍了在Asp.Net MVC项目中如何记录错误日志并保存到本地txt文件。通过创建继承自HandleErrorAttribute的ErrorLog类,重写OnException方法,配置FilterConfig.cs,并在Global.asax中注册,可以实现错误捕获和日志记录。举例说明了在图片上传过程中如何触发和记录异常。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

为了方便查询系统出错弄个错误日志出来对于维护来说是很有必要的。
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文件夹下面的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、下面的效果
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值