在C#应用中接入Prometheus监控,核心是通过客户端库定义业务指标,然后暴露HTTP端点供Prometheus服务定时拉取数据。这种方式不需要额外依赖中间件,实现成本较低,适合大多数.NET应用接入。

环境准备与依赖安装
首先需要在C#项目中安装Prometheus官方提供的.NET客户端库,目前主流的库是prometheus-net,支持.NET Framework和.NET Core/.NET 5及以上版本。如果是ASP.NET Core项目,还需要安装对应的宿主扩展包。
通过NuGet安装依赖的命令如下:
# 基础客户端库 Install-Package prometheus-net # ASP.NET Core宿主扩展(如果是Web项目) Install-Package prometheus-net.AspNetCore
基础指标定义与暴露
常用指标类型
Prometheus支持四种核心指标类型,在C#客户端中都有对应的实现:
- Counter:只增不减的计数器,适合统计请求总数、错误次数等场景
- Gauge:可增可减的数值指标,适合统计当前在线人数、内存使用量等场景
- Histogram:直方图指标,适合统计请求耗时、响应大小等分布数据
- Summary:摘要指标,类似直方图,会直接计算分位数数据
定义自定义指标
可以在应用的业务代码中直接定义需要的指标,以下是Counter和Gauge的示例:
using Prometheus;
public class AppMetrics
{
// 定义请求总数计数器,添加标签区分不同接口
public static readonly Counter RequestTotal = Metrics.CreateCounter(
"app_request_total",
"应用总请求数",
new[] { "path", "method", "status_code" }
);
// 定义当前在线人数仪表盘
public static readonly Gauge OnlineUserCount = Metrics.CreateGauge(
"app_online_user_count",
"当前在线用户数"
);
}
暴露指标端点
如果是ASP.NET Core项目,只需要在启动配置中添加指标中间件即可暴露/metrics端点:
var builder = WebApplication.CreateBuilder(args); // 添加Prometheus监控中间件(非Web项目不需要这一步) builder.Services.AddControllers(); var app = builder.Build(); // 暴露/metrics端点,供Prometheus拉取数据 app.UseMetricServer(); app.MapControllers(); app.Run();
如果是控制台应用,需要手动启动一个HTTP服务暴露端点:
using System.Net;
using Prometheus;
var listener = new HttpListener();
listener.Prefixes.Add("http://localhost:9182/metrics/");
listener.Start();
Console.WriteLine("指标端点已启动:http://localhost:9182/metrics/");
while (true)
{
var context = listener.GetContext();
// 将指标数据写入响应
Metrics.DefaultRegistry.CollectAndExportAsTextAsync(context.Response.OutputStream);
context.Response.Close();
}
指标上报与验证
在业务代码中调用定义好的指标即可完成数据上报,以下是控制器中的使用示例:
using Microsoft.AspNetCore.Mvc;
[ApiController]
[Route("api/[controller]")]
public class TestController : ControllerBase
{
[HttpGet]
public IActionResult Get()
{
// 上报请求总数,标签对应path、method、status_code
AppMetrics.RequestTotal.Labels("/api/test", "GET", "200").Inc();
// 模拟在线人数变化
AppMetrics.OnlineUserCount.Inc();
return Ok("请求成功");
}
}
启动应用后,访问http://localhost:9182/metrics/(端口根据实际配置调整),可以看到如下格式的指标数据:
# HELP app_request_total 应用总请求数
# TYPE app_request_total counter
app_request_total{path="/api/test",method="GET",status_code="200"} 1
# HELP app_online_user_count 当前在线用户数
# TYPE app_online_user_count gauge
app_online_user_count 1
Prometheus服务端配置
在Prometheus的配置文件prometheus.yml中添加对应的抓取任务:
scrape_configs:
- job_name: "csharp-app"
# 应用暴露的metrics端点地址
static_configs:
- targets: ["localhost:9182"]
重启Prometheus服务后,在Prometheus的Web界面中查询app_request_total即可看到对应的指标数据,说明C#应用的指标已经成功暴露并被Prometheus采集。
注意事项
- 指标名称需要符合Prometheus的命名规范,使用下划线分隔单词,避免使用特殊字符
- 标签的数量不要过多,否则会导致指标基数过大,影响Prometheus性能
- 生产环境建议给指标端点添加认证,避免指标数据被未授权访问
- 如果应用部署在Kubernetes中,可以通过ServiceMonitor自动发现指标端点,不需要手动配置每个应用的地址
C#Prometheus应用指标metric_exporter修改时间:2026-06-23 08:00:17