Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Log duration of an ASP Web API action

I am using an ActionFilter to log all action calls of my ASP.NET Web API project. The OnActionExecuted method tells a lot about what's been happening.

I just can't figure out how to find an efficient way to measure execution time...

like image 858
RooSoft Avatar asked Jun 12 '13 15:06

RooSoft


1 Answers

Something like this should do the trick...

public class StopwatchAttribute : ActionFilterAttribute
{
    private const string StopwatchKey = "StopwatchFilter.Value";

    public override void OnActionExecuting(HttpActionContext actionContext)
    {
        base.OnActionExecuting(actionContext);

        actionContext.Request.Properties[StopwatchKey] = Stopwatch.StartNew();
    }

    public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
    {
        base.OnActionExecuted(actionExecutedContext);

        Stopwatch stopwatch = (Stopwatch)actionExecutedContext.Request.Properties[StopwatchKey];
        // TODO something useful with stopwatch.Elapsed
        Trace.WriteLine("Elapsed = " + stopwatch.Elapsed);
    }
}

Here we store a new Stopwatch in the request properties and stop it when the request has completed.

like image 64
Dean Ward Avatar answered Nov 03 '22 04:11

Dean Ward