Prometheus.NET - .NET应用的监控利器
1. 项目介绍
Prometheus.NET 是一个 .NET 库,用于在应用程序中添加监控指标,并将这些指标导出至 Prometheus 监控系统。它支持多种运行时环境,包括 .NET Framework 4.6.2 和 .NET 6.0。通过该库,开发者可以轻松地为自己的应用添加监控功能,从而实现对应用性能和健康状况的实时监控。
2. 项目快速启动
以下是一个基于 .NET 6 控制台应用程序模板的快速启动示例:
using var server = new Prometheus.KestrelMetricServer(port: 1234);
server.Start();
Console.WriteLine("Open http://localhost:1234/metrics in a web browser.");
Console.WriteLine("Press enter to exit.");
Console.ReadLine();
这段代码会启动一个 Kestrel 服务器,并在端口 1234 上提供 /metrics
HTTP 服务。你可以在浏览器中访问该服务来查看当前应用的监控指标。
3. 应用案例和最佳实践
案例一:计数器(Counter)
计数器用于追踪只能递增的指标,如处理的工作数量。
private static readonly Counter ProcessedJobCount = Metrics.CreateCounter("myapp_jobs_processed_total", "Number of processed jobs.");
// 在处理工作的地方
ProcessedJobCount.Inc();
案例二:仪表(Gauge)
仪表可以用来追踪任意数值指标,如队列中的工作数量。
private static readonly Gauge JobsInQueue = Metrics.CreateGauge("myapp_jobs_queued", "Number of jobs waiting for processing in the queue.");
// 当工作入队时
JobsInQueue.Inc();
// 当工作出队时
JobsInQueue.Dec();
案例三:直方图(Histogram)
直方图可以追踪事件的大小和数量,并计算分位数。
private static readonly Histogram OrderValueHistogram = Metrics.CreateHistogram("myapp_order_value_usd", "Histogram of received order values (in USD).", new HistogramConfiguration
{
Buckets = Histogram.LinearBuckets(start: 100, width: 100, count: 10)
});
// 在观测订单值的地方
OrderValueHistogram.Observe(order.TotalValueUsd);
案例四:摘要(Summary)
摘要用于追踪指标的趋势,如请求处理的持续时间。
private static readonly Summary RequestDurationSummary = Metrics.CreateSummary("myapp_request_duration_seconds", "Summary of request duration");
// 在处理请求的开始和结束
RequestDurationSummary.StartTimer();
// 处理请求的逻辑...
RequestDurationSummary.StopTimer();
4. 典型生态项目
Prometheus.NET 的生态系统中包括多个用于不同场景的项目:
prometheus-net.AspNetCore
:为 ASP.NET Core 应用提供中间件和独立的 Kestrel 指标服务器。prometheus-net.AspNetCore.HealthChecks
:整合 ASP.NET Core 健康检查。prometheus-net.AspNetCore.Grpc
:为 ASP.NET Core gRPC 服务提供监控。prometheus-net.NetFramework.AspNet
:为 .NET Framework Web API 提供中间件。
通过使用这些生态项目,开发者可以更方便地将 Prometheus 监控集成到不同的 .NET 应用中。