ASP.NET MVC 异常捕获

代码异常捕获分两种,一种是自己使用了try catch进行捕获,还一种是没有异常捕获,就会有个全局的异常,在global里面

  public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            //默认注册全局的错误处理的过滤器。
            filters.Add(new MyExceptionFilterAttribute());
        }

异常会从很多地方发生,有自己捕获的,有全局的,所以我们需要一个入口,既可以试自己捕获的异常写入到日志中,还可以使全局异常写入到日志中。

我们需要从写这个方法, 只需要继承这个接口并从写,就可以了,自己捕获异常的地方,直接调用这个写入日志方法就可以实现所有的异常写入到日志中了。

 public class MyExceptionFilterAttribute:HandleErrorAttribute
    {
        public override void OnException(ExceptionContext filterContext)
        {
            base.OnException(filterContext);

            //处理错误消息。跳转到一个错误也页面
            ///using(Sql)
            Common.LogHelper.WriteLog(filterContext.Exception.ToString());

            //页面跳转到错误页面
            filterContext.HttpContext.Response.Redirect("/Error.html");
            
        }
    }

使用Log4NET写异常。

  public static void WriteLog(string txt)
        {

            //Log4net   log4j

            ILog log = log4net.LogManager.GetLogger("log4netlogger");

            log.Error(txt);
}

在global里面的aciton方法需要对log4net进行一下设置

  //配置log4net日志
            log4net.Config.XmlConfigurator.Configure();

一般都是使用log4net,如果不适用的话,需要考虑线程安全和并发,线程安全好解决,直接用一个锁lock(“ss”)随便锁一个字符串即可,或者采用本地数据Queue,就是线程安全的。

  public static Queue<string> LogTextQueue = new Queue<string>();
LogTextQueue.Enqueue(txt);


//在globla里面的action需要写一个方法,开启一个线程,随时读取错误日志并写道文件中
 ThreadPool.QueueUserWorkItem(s =>
           {

                 while (true)
                {
                     string str = Common.LogHelper.LogTextQueue.Dequeue();
               Console.WriteLine(str);//真写日志里
                    Thread.Sleep(300);
              }
            

    });