zoukankan      html  css  js  c++  java
  • 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、效果

  • 相关阅读:
    java 简单封装resultMap返回对象为map
    freemarker 遍历树形菜单
    python 正则表达式
    python BeautifulSoup基本用法
    sublime中正则替换
    媒体查询
    响应式网站的优点和缺点
    响应式网站概念
    vue系列之vue-resource
    vue系列之项目打包以及优化(最新版)
  • 原文地址:https://www.cnblogs.com/w5942066/p/10882347.html
Copyright © 2011-2022 走看看