如何在 ASP.NET 4.7.1 中报告 Prometheus-net 指标

Vla*_*lad 5 c# asp.net asp.net-mvc prometheus-net

如何在常规 ASP.NET 4.7.1 应用程序中使用 prometheus-net?在 .Net Core 中很容易,但我找不到在 4.7.1 中向 Grafana 报告指标的好方法

理想的情况是拥有/metrics报告指标的路径。

我试图创建一个粗略的测试控制器来运行,MetricServer但出现错误。

// horrible test code
[RoutePrefix("metrics")]
public class MetricsController : ApiController
{
    static readonly MetricServer _server = new MetricServer(7777);

    static MetricsController()
    {
        _server.Start();
    }

    [Route("")]
    public async Task<IHttpActionResult> Get()
    {
        using (var client = new HttpClient())
        {
            var metrics = await client.GetAsync("http://localhost:7777/metrics");
            return Content(HttpStatusCode.OK, await metrics.Content.ReadAsStringAsync(),null, metrics.Content.Headers.ContentType.ToString());
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

System.Net.HttpListenerException: '访问被拒绝'

Roc*_*lan 5

还有另一种方法可以做到这一点。MetricServer您可以通过调用自行收集指标,而不是在启动时创建一个新的并调用它CollectAndExportAsTextAsync

只需创建一个如下所示的 WebApi 控制器:

public class MetricsController : ApiController
{
    [Route("metrics")]
    [HttpGet]
    public async Task<HttpResponseMessage> AppMetrics()
    {
        using (MemoryStream ms = new MemoryStream())
        {
            await Metrics.DefaultRegistry.CollectAndExportAsTextAsync(ms);
            ms.Position = 0;

            using (StreamReader sr = new StreamReader(ms))
            {
                var allmetrics = await sr.ReadToEndAsync();

                return new HttpResponseMessage()
                {
                    Content = new StringContent(allmetrics, Encoding.UTF8, "text/plain")
                };
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

或者您可以只使用我的 NuGet 包,它还为您提供 HTTP 指标和一些 SQL 指标 - https://www.nuget.org/packages/prometheus-net.AspNet/


Ser*_*e K 3

MetricServer.Start()如果您的用户无权在指定端口上打开 Web 服务器,则可能会在 Windows 上引发访问拒绝异常。您可以使用 netsh 命令授予自己所需的权限:

netsh http add urlacl url=http://+:7777/metrics user=DOMAIN\user

Run Code Online (Sandbox Code Playgroud)