为了方便查询系统出错弄个错误日志出来对于维护运维来说是很有必要的。

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、下面的效果