码迷,mamicode.com
首页 > Web开发 > 详细

.net MVC中异常日志

时间:2016-08-29 17:33:34      阅读:135      评论:0      收藏:0      [点我收藏+]

标签:

    在日常工作中,我们有些项目可能进入了维护期,但是项目可能存在一些潜伏较深的bug导致我们在测试阶段并未发现,那么错误日志记录为我们的项目维护起着重要的作用。记录系统日志的方法如下

   1.在系统根目录建立Log文件夹

   2.创建异常类,且该类继承FilterAttribute, IExceptionFilter

public class LogExceptionFilterAttribute : FilterAttribute, IExceptionFilter
{
      private string ErrPath = System.Web.HttpContext.Current.Server.MapPath("/Log");
  /// <summary>
  /// 重写异常方法
  /// </summary>
  /// <param name="filterContext"></param>
  public void OnException(ExceptionContext filterContext)
  {
    if (!Directory.Exists(ErrPath))
    {
      Directory.CreateDirectory(ErrPath);
    }
    File.AppendAllText(ErrPath + "/" + DateTime.Now.Date.ToString("yyyy-MM-dd") + ".txt", filterContext.Exception.Message + "\r\n对象:" + filterContext.Exception.Source + "\r\n方法:" + filterContext.Exception.TargetSite + "\r\n字符串:" + filterContext.Exception.StackTrace + "\r\n时间:" + DateTime.Now + "\r\n" + HttpContext.Current.Request.Url.PathAndQuery + "\r\n----------------------------------\r\n\r\n\r\n\r\n");
  }
}

 

  3.注册全局过滤器

  找到App_start文件夹下的filterconfig类,并注册异常过滤器

public class FilterConfig
{
  public static void RegisterGlobalFilters(GlobalFilterCollection filters)
  {
    filters.Add(new LogExceptionFilterAttribute());
    filters.Add(new HandleErrorAttribute());
  }
}

 

4.此时若系统中有异常出现,在该异常信息会被记录在Log文件夹下,但是系统异常最好创建一个友好的错误提示页面

.net MVC中异常日志

标签:

原文地址:http://www.cnblogs.com/niguang/p/5818467.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!