Prometheus 指标在 C# (.NET) 中的集成:完整指南
Prometheus 是一个开源监控系统,用于收集和存储时间序列形式的指标。对于 C# (.NET) 开发者来说,与 Prometheus 集成可以实时跟踪应用程序性能、业务指标和系统状态。本文将详细介绍如何将 Prometheus 连接到 .NET 应用程序、使用哪些库以及如何正确配置指标。
为什么在 .NET 中需要 Prometheus 指标?
使用 Prometheus 进行监控可以实现:
- 跟踪请求数量、错误数和响应时间。
- 收集性能指标(CPU、内存、GC)。
- 创建自定义业务指标(活跃用户、订单数)。
- 与 Grafana 集成以实现仪表盘可视化。
- 基于阈值配置告警。
prometheus-net 库
在 .NET 中与 Prometheus 配合使用的主要库是 prometheus-net。它支持 ASP.NET Core、.NET Core、.NET Framework 和 gRPC。通过 NuGet 安装:
dotnet add package prometheus-net对于 ASP.NET Core,还需额外安装:
dotnet add package prometheus-net.AspNetCorePrometheus 指标类型
该库支持所有标准指标类型:
- Counter — 只增不减的计数器(请求数量)。
- Gauge — 可增可减的值(当前温度)。
- Histogram — 用于测量值分布情况的直方图(响应时间)。
- Summary — 用于数据聚合的分位数(p95、p99)。
示例:基本 Counter
创建一个统计端点请求数量的指标:
using Prometheus;
public class MetricsService{ private static readonly Counter RequestCount = Metrics .CreateCounter("app_requests_total", "Total number of requests", new CounterConfiguration { LabelNames = new[] { "method", "endpoint" } });
public void RecordRequest(string method, string endpoint) { RequestCount.WithLabels(method, endpoint).Inc(); }}在 ASP.NET Core 控制器中的调用方式如下:
[ApiController][Route("api/order")]public class OrderController : ControllerBase{ private readonly MetricsService _metrics;
public OrderController(MetricsService metrics) => _metrics = metrics;
[HttpGet] public IActionResult GetOrders() { _metrics.RecordRequest("GET", "/api/order"); return Ok(new { orders = new[] { "order1", "order2" } }); }}示例:用于活跃用户的 Gauge
private static readonly Gauge ActiveUsers = Metrics .CreateGauge("app_active_users", "Number of active users");
public void UserLoggedIn() => ActiveUsers.Inc();public void UserLoggedOut() => ActiveUsers.Dec();示例:用于响应时间的 Histogram
private static readonly Histogram RequestDuration = Metrics .CreateHistogram("app_request_duration_seconds", "Request duration in seconds", new HistogramConfiguration { Buckets = Histogram.ExponentialBuckets(0.001, 2, 10) // 从 1ms 到约 1s });
public void RecordRequestDuration(double seconds){ RequestDuration.Observe(seconds);}在 ASP.NET Core 中导出指标
为了让 Prometheus 能够收集指标,需要添加 /metrics 端点。在 Program.cs 中:
using Prometheus;
var builder = WebApplication.CreateBuilder(args);builder.Services.AddCont