MVC过滤器全局异常捕捉

    技术2022-07-10  163

    1、首先引用log4net.dll 2、LogExceptionAttribute.cs文件

    [AttributeUsage(AttributeTargets.Class, Inherited = true, AllowMultiple = false)] public class LogExceptionAttribute : HandleErrorAttribute { public override void OnException(ExceptionContext filterContext) { if (!filterContext.ExceptionHandled) { string controllerName = (string)filterContext.RouteData.Values["controller"]; string actionName = (string)filterContext.RouteData.Values["action"]; string msgTemplate = "在执行 controller[{0}] 的 action[{1}] 时产生异常"; LoggerHelper.Error(string.Format(msgTemplate, controllerName, actionName), filterContext.Exception); } if (filterContext.Result is JsonResult) { //当结果为json时,设置异常已处理 filterContext.ExceptionHandled = true; } else { //否则调用原始设置 base.OnException(filterContext); } } }

    3、Global文件配置如下

    //注册 log4net log4net.Config.XmlConfigurator.Configure( new System.IO.FileInfo(AppDomain.CurrentDomain.BaseDirectory + "log4net.config") );

    4、FilterConfig配置

    public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new HandleErrorAttribute()); filters.Add(new LogExceptionAttribute()); }

    5、log4net.config

    <?xml version="1.0"?> <configuration> <configSections> <section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net"/> </configSections> <log4net> <!--错误日志--> <appender name="RollingLogFileAppender" type="log4net.Appender.RollingFileAppender"> <file value="log\\LogError\\"/> <appendToFile value="true"/> <rollingStyle value="Date"/> <datePattern value="yyyy\\yyyyMM\\yyyyMMdd'.txt'"/> <staticLogFileName value="false"/> <param name="MaxSizeRollBackups" value="100"/> <layout type="log4net.Layout.PatternLayout"> <!--每条日志末尾的文字说明--> <!--输出格式--> <!--样例:2008-03-26 13:42:32,111 [10] INFO Log4NetDemo.MainClass [(null)] - info--> <conversionPattern value="%newline %n记录时间:
    转载请注明原文地址:https://ipadbbs.8miu.com/read-591.html
    最新回复(0)