LSTANCZYK
3/21/2017 - 4:43 PM

StatsdActionFilter

using System.Web;
using System.Web.Mvc;
using StatsdClient;
using Stopwatch = System.Diagnostics.Stopwatch;

namespace MvcApplication1.Controllers
{
    public class StatsdActionFilter : ActionFilterAttribute
    {
        private const string StopwatchKey = "stopwatch";

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            var stopwatch = new Stopwatch();
            stopwatch.Start();
            HttpContext.Current.Items.Add(StopwatchKey, stopwatch);
        }

        public override void OnResultExecuted(ResultExecutedContext filterContext)
        {
            var stopwatch = HttpContext.Current.Items[StopwatchKey] as Stopwatch;
            if (stopwatch == null) return;

            stopwatch.Stop();
            Metrics.Timer(
                filterContext.RouteData.Values["controller"] + "." + filterContext.RouteData.Values["action"],
                (int) stopwatch.ElapsedMilliseconds);
        }
    }
}