MVC异常处理

使用Nlog记录异常信息

首先引用NLog的dll文件,修改配置文件,在configuration下的configSections节点下,配置Nlog关联的配置节例如 <section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog" /> ,在configuration节点下配置nlog日志输出路径配置

<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <targets>
      <target name="fileLog" type="File" fileName="${basedir}/Log/${shortdate}/${level}.txt" layout="【${date:format=yyyy-MM-dd HH\:mm\:ss}】【${level}】 ${message} ${exception}" />
    </targets>
    <rules>
      <logger name="*" minlevel="Debug" writeTo="fileLog" />
    </rules>
  </nlog>

新建一个继承自HandleErrorAttribute的特性,用于处理异常,代码如下

public class CustomerExceptionAttribute:HandleErrorAttribute
    {
        /// <summary>
        /// 异常处理
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnException(ExceptionContext filterContext)
        {
            NLog.LogManager.GetCurrentClassLogger().Error(filterContext.Exception);
            base.OnException(filterContext);
            filterContext.HttpContext.Response.Redirect("");
        } 
    }

在需要处理异常的地方添加该特性

        [CustomerException]
        public ActionResult Index()
        {
            int a = 0;
            int b = 3 / a;
            return View();
        }

 

posted @ 2015-05-18 14:45  学习不止步  阅读(112)  评论(0)    收藏  举报