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

.net mvc 运行监控和错误捕捉

时间:2017-12-15 17:24:08      阅读:281      评论:0      收藏:0      [点我收藏+]

标签:pre   cti   star   method   summary   try   query   monit   pos   

方法类

技术分享图片
/// <summary>
    /// 运行监控类
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
    public class StatisticsTrackerAttribute : ActionFilterAttribute
    {
        private readonly string Key = "_thisOnActionMonitorLog_";

        #region Action运行监控
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            MonitorLog MonLog = new MonitorLog();
            MonLog.ExecuteStartTime = Convert.ToDateTime(DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss.ffff", DateTimeFormatInfo.InvariantInfo));
            MonLog.ControllerName = filterContext.RouteData.Values["controller"] as string;
            MonLog.ActionName = filterContext.RouteData.Values["action"] as string;
            //获取Action的自定义属性
            var attributes = filterContext.ActionDescriptor.GetCustomAttributes(typeof(ActionDescribeAttribute), true);
            if (attributes != null && attributes.Length > 0)
            {
                ActionDescribeAttribute myAttribute = attributes[0] as ActionDescribeAttribute;
                if (myAttribute != null)
                {
                    MonLog.ActionInstructions = myAttribute.DisplayName;
                }
            }
            filterContext.Controller.ViewData[Key] = MonLog;
            base.OnActionExecuting(filterContext);

        }

        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            MonitorLog MonLog = filterContext.Controller.ViewData[Key] as MonitorLog;
            MonLog.ExecuteEndTime = Convert.ToDateTime(DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss.ffff", DateTimeFormatInfo.InvariantInfo));
            MonLog.FormCollections = filterContext.HttpContext.Request.Form;//form表单提交的数据
            MonLog.QueryCollections = filterContext.HttpContext.Request.QueryString;//Url 参数
            MonLog.AbsoluteUri = filterContext.HttpContext.Request.Url.AbsoluteUri;
            base.OnActionExecuted(filterContext);
        }
        #endregion

        #region View 视图生成时间监控
        public override void OnResultExecuting(ResultExecutingContext filterContext)
        {
            MonitorLog MonLog = filterContext.Controller.ViewData[Key] as MonitorLog;
            MonLog.ResultExecuteStartTime = Convert.ToDateTime(DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss.ffff", DateTimeFormatInfo.InvariantInfo));
            base.OnResultExecuting(filterContext);

        }
        public override void OnResultExecuted(ResultExecutedContext filterContext)
        {
            MonitorLog MonLog = filterContext.Controller.ViewData[Key] as MonitorLog;
            MonLog.ResultExecuteEndTime = Convert.ToDateTime(DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss.ffff", DateTimeFormatInfo.InvariantInfo));
            //写日志
            filterContext.Controller.ViewData.Remove(Key);
            MonLog.GetLoginfo();
            base.OnResultExecuted(filterContext);
        }

        #endregion

    }
    /// <summary>
    /// 程序运行错误  收集器
    /// </summary>
    [AttributeUsage(AttributeTargets.Class, Inherited = true, AllowMultiple = false)]
    public class LogExceptionAttribute : HandleErrorAttribute
    {
        public override void OnException(ExceptionContext filterContext)
        {
            if (!filterContext.ExceptionHandled)
            {
                try
                {
                    string sForm = this.GetCollections(filterContext.HttpContext.Request.Form);
                    string sQuery = this.GetCollections(filterContext.HttpContext.Request.QueryString);
                    string ControllerName = string.Format("{0}Controller", filterContext.RouteData.Values["controller"] as string);
                    string ActionName = filterContext.RouteData.Values["action"] as string;
                    string message = string.Format(@"
                                    在执行 controller[{0}] 的 action[{1}] 时产生异常。
                                    异常类型:{2}
                                    <br>异常内容:{3}
                                    <br>引发异常的方法:{4}
                                    <br>引发异常源:{5}
                                    <br>参数:{6}"
                        , ControllerName
                        , ActionName
                    , filterContext.Exception.GetType().Name
                    , filterContext.Exception.Message
                     , filterContext.Exception.TargetSite
                     , filterContext.Exception.Source + filterContext.Exception.StackTrace
                     , sForm + sQuery
                     );
                    //记录日志
                    LoggerBusiness.WriteLog(message, "Web程序运行错误");
                }
                catch (Exception)
                {

                }

                base.OnException(filterContext);
            }
        }

        /// <summary>
        /// 获取Post 或Get 参数
        /// </summary>
        /// <param name="Collections"></param>
        /// <returns></returns>
        public string GetCollections(NameValueCollection Collections)
        {
            string Parameters = string.Empty;
            if (Collections == null || Collections.Count == 0)
            {
                return Parameters;
            }
            foreach (string key in Collections.Keys)
            {
                Parameters += string.Format("{0}:{1};", key, Collections[key]);
            }
            if (!string.IsNullOrWhiteSpace(Parameters) && Parameters.EndsWith(";"))
            {
                Parameters = Parameters.Substring(0, Parameters.Length - 1);
            }
            return Parameters;
        }
    }

 /// <summary>
    /// 描述属性
    /// </summary>
    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, AllowMultiple = false)]
    public class ActionDescribeAttribute : Attribute
    {
        public string DisplayName { get; set; }

        public ActionDescribeAttribute()
        {
            this.DisplayName = "";
        }
View Code

使用方法

技术分享图片
 1    [StatisticsTrackerAttribute]
 2     [LogException]
 3     public class ManageController : Controller
 4     {
 5         //
 6         // GET: /Manage/
 7         [ActionDescribe(DisplayName="加载首页")]
 8         public ActionResult Index()
 9         {
10             return View();
11         }
12     }
View Code

 

.net mvc 运行监控和错误捕捉

标签:pre   cti   star   method   summary   try   query   monit   pos   

原文地址:http://www.cnblogs.com/dahuo/p/8044003.html

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