ASP.NET MVC WEB実行タイムフィルタ

3105 ワード

すべてのインタフェースに実行時間のモニタリングを容易にするために、フィルタを1つ追加すればよい.
using System;
using System.Diagnostics;
using System.Linq;
using System.Web.Http.Controllers;
using System.Web.Http.Filters;

namespace api.Filters
{
    /// 
    ///       
    /// 
    public class TimingActionFillter : ActionFilterAttribute
    {

        private const string Key = "__action_duration__";

        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            if (SkipLogging(actionContext))
            {
                return;
            }
            var stopWatch = new Stopwatch();
            actionContext.Request.Properties[Key] = stopWatch;
            stopWatch.Start();
        }

        public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
        {
            if (!actionExecutedContext.Request.Properties.ContainsKey(Key))
            {
                return;
            }

            var stopWatch = actionExecutedContext.Request.Properties[Key] as Stopwatch;
            if (stopWatch != null)
            {
                stopWatch.Stop();
                var actionName = actionExecutedContext.ActionContext.ActionDescriptor.ActionName;
                var controllerName = actionExecutedContext.ActionContext.ActionDescriptor.ControllerDescriptor.ControllerName;
                //var parameters = actionExecutedContext.ActionContext.Request.RequestUri.Host;
                //var response = actionExecutedContext.ActionContext.Response.Content.ToString();
                //Debug.Print(string.Format("[Execution of{0}- {1} took {2}.]", controllerName, actionName, stopWatch.Elapsed));

                string content = $" {AppendSpace(controllerName, 30)}| {AppendSpace(actionName,30)}| { AppendSpace(stopWatch.ElapsedMilliseconds+"ms",12)}| ";
                content += $"level={AppendSpace((stopWatch.ElapsedMilliseconds / 100).ToString(), 12)}| ";
                //content += $"request={parameters}| ";
                //content += $"response={response}";
                PT.Utilities.LogHelper.TimeLog(content);
            }

        }

        private static bool SkipLogging(HttpActionContext actionContext)
        {
            return actionContext.ActionDescriptor.GetCustomAttributes().Any() ||
                    actionContext.ControllerContext.ControllerDescriptor.GetCustomAttributes().Any();
        }

        private string AppendSpace(string str, int length)
        {
            int strLen = str.Length;
            str = (str ?? "").Trim();
            if (str.Length >= length) return str;
            for (int i = 0; i < length - strLen; i++)
                str += " ";
            return str;
        }
    }

    [AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true)]
    public class NoLogAttribute : Attribute
    {

    }
}

次に対応するクラス名に[TimingActionFillter]と書き、apicontrollerの継承のみが有効になります.