How to get the request processing time in Asp.net mvc?

前端 未结 2 1369
名媛妹妹
名媛妹妹 2021-01-24 20:55

I want to log the request processing time for Asp.Net MVC application. I can get \'time-taken\' from IIS logs but this time includes the network time taken to

2条回答
  •  迷失自我
    2021-01-24 21:19

    You can create a filter to intercept action execution time.

     public class ActionTiming :ActionFilterAttribute {
        private static readonly ILog Logger = LogManager.GetLogger("TimingLogger");
        private string controllerName = string.Empty;
        private string actionName = string.Empty;
    
        private Stopwatch intertime = Stopwatch.StartNew();
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            intertime.Restart();
            controllerName = filterContext.RouteData.Values["controller"].ToString();
            actionName = filterContext.RouteData.Values["action"].ToString();
            var message = string.Format("{0} controller: {1} action: {2}", "OnActionExecuting", controllerName, actionName);
            Logger.Info(message);
    
        }
    
        public override void OnResultExecuted(ResultExecutedContext filterContext)
        {
    
            var message = string.Format("{0} controller: {1} action: {2}, time (ms): {3}", "OnResultExecuted", controllerName, actionName, intertime.ElapsedMilliseconds);
            Logger.Info(message);
        }
    
    
    }
    

    Then, you can register this filter globally in Application_Start or use it as attribute.

提交回复
热议问题