C# (.NET) 中的 Prometheus 指标 — prometheus-net 库
在现代 .NET 平台上的 Web 应用程序和微服务开发中,监控和可观测性已成为生产环境的必备要素。prometheus-net 库是 .NET 的官方客户端库,它允许您轻松地以 Prometheus 监控服务器能够理解的格式导出应用程序指标。
借助 prometheus-net,您可以收集性能数据(响应时间、请求数量、错误、内存使用情况),并将其传输到 Prometheus,以便随后在 Grafana 或其他工具中进行可视化。该库同时支持旧版 .NET Framework (4.6.1+) 和现代 .NET Core / .NET 5/6/7/8。
安装
您可以通过 NuGet 包管理器或使用 .NET CLI 安装该库:
dotnet add package prometheus-net对于 ASP.NET Core 应用程序,还需要 prometheus-net.AspNetCore 包:
dotnet add package prometheus-net.AspNetCore主要指标类型
Prometheus 支持四种主要指标类型。在 prometheus-net 中,它们作为 Metrics 类中的静态工厂实现:
- Counter — 只能递增的计数器(例如,已处理的请求数量)。
- Gauge — 既可以增加也可以减少的指标(例如,活动连接数或当前温度)。
- Histogram — 直方图,用于计算指定区间(桶)内的观测数量。用于测量响应时间或数据大小的分布。
- Summary — 汇总指标,基于观测流计算分位数(p50、p95、p99)。
Counter 使用示例
让我们创建一个简单的计数器来计算已处理的 HTTP 请求数量:
using Prometheus;
// 创建一个带有名称和描述的计数器private static readonly Counter RequestCount = Metrics .CreateCounter("myapp_requests_total", "Total number of HTTP requests.");
// 在请求处理程序中增加计数器public IActionResult Index(){ RequestCount.Inc(); // 增加 1 // 或者 RequestCount.Inc(5); // 增加 5 return View();}Gauge 使用示例
Gauge 适用于跟踪当前状态,例如活动用户数量:
private static readonly Gauge ActiveUsers = Metrics .CreateGauge("myapp_active_users", "Number of active users.");
// 用户登录时ActiveUsers.Inc();
// 用户退出时ActiveUsers.Dec();Histogram 使用示例
直方图非常适合测量请求执行时间:
private static readonly Histogram RequestDuration = Metrics .CreateHistogram("myapp_request_duration_seconds", "Histogram of request duration.", new HistogramConfiguration { // 配置桶的边界 Buckets = new[] { 0.1, 0.25, 0.5, 1.0, 2.5 } });
// 在中间件或控制器操作中using (RequestDuration.NewTimer()){ // 执行请求 await Next(context);}与 ASP.NET Core 集成
要使您的 /metrics 端点开始以 Prometheus 格式提供数据,只需在 Program.cs 中添加中间件即可:
using Prometheus;
var builder = WebApplication.CreateBuilder(args);var app = builder.Build();
// 添加中间件以收集