如何跟踪和记录性能并调用我的Web API请求?

时间:2016-06-27 07:13:19

标签: c# asp.net-web-api nlog

我只是在C#中使用了非常糟糕的Web API代码。我需要改进它,但我不知道从哪里开始。有很多课程,代码是一场噩梦。我还认为部分代码从未使用过。

我想计算每个请求被调用的时间以及每个请求的持续时间。我想将所有结果记录在表格中。在一两天内,我可以清楚地看到我最常用的东西和需要时间的东西。客户抱怨这一点。

我使用Nlog进行日志,使用简单的秒表来计算性能。你有什么建议?我知道最好对跟踪使用Filter和属性,但是如何记录和跟踪这样的性能呢?

// GET api/Item/5
public Item GetItem(string id)
{
    // I don't use string.Format in my real code. This is just for this example.
    logger.Trace(string.Format("Request: GET api/Item/{0}", id));
    Stopwatch sw = new Stopwatch();
    sw.Start();

    Item item = context.Items.Single(i => i.Code == id);

    sw.Stop();
    logger.Trace(string.Format("Response: GET api/values/{0}\r\nElpased={1}\r\rn{2}", id, sw.Elapsed, response));

我在此处找到了以前的信息

感谢

http://weblogs.asp.net/fredriknormen/log-message-request-and-response-in-asp-net-webapi

Exact time measurement for performance testing

当然,所有这些跟踪和性能作业都将从我的配置文件中激活或停用。对于NLog来说,它是内置的。对于秒表我计划构建一些东西。我不打算在制作上一直保持这种生存

3 个答案:

答案 0 :(得分:1)

您可以使用DelegatingHandler

  

HTTP处理程序的基本类型,它将HTTP响应消息的处理委托给另一个处理程序,称为内部处理程序。

enter image description here

在管道中注入允许在控制器中的请求处理之前和之后捕获位置。

public class MonitoringDelegate : DelegatingHandler
{
    protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
    {
    var watcher = Stopwatch.StartNew();
    var response = await base.SendAsync(request, cancellationToken);
    watcher.Stop();

    //log/store duration using watcher.ElapsedMilliseconds

    return response;
    }
}

答案 1 :(得分:-1)

这是一种更好的记录性能的方法:http://arcware.net/logging-web-api-requests/

请求时间和响应时间之间的时差是经过的时间。

答案 2 :(得分:-2)

查看分析器。这种更通用的方法。我们使用Ants performance profiler