c#跨平台metrics监控首选eventcounter+dotnet-counters组合,因performancecounter严重依赖windows etw和注册表,在linux/macos抛platformnotsupportedexception,无法获取cpu/内存等核心指标;eventcounter基于eventpipe,轻量跨平台,开销微秒级。

直接说结论:C#中做Metrics指标监控,首选 EventCounter + dotnet-counters 组合,而非传统 PerformanceCounter;跨平台部署时 PerformanceCounter 在 Linux/macOS 上基本不可用。
为什么不能用 PerformanceCounter 做跨平台 Metrics?
PerformanceCounter 严重依赖 Windows ETW 和注册表,Linux/macOS 上调用会直接抛出 PlatformNotSupportedException。即使在 .NET 6+ 中启用兼容模式,也无法读取进程级 CPU/内存等核心指标——它根本不是为跨平台设计的。
- 错误现象:
System.PlatformNotSupportedException: Performance counters are not supported on this platform - 适用场景:仅限 Windows 服务或遗留桌面应用的单机监控
- 替代方案:必须切换到
EventCounter或第三方库(如App.Metrics)
EventCounter 是什么?怎么快速暴露一个自定义指标?
EventCounter 是 .NET 运行时原生支持的轻量级、跨平台指标发布机制,通过 EventSource 背后自动对接 EventPipe,无需额外依赖,且开销极低(微秒级)。
关键实操点:
- 必须继承
EventSource,但不需标记[Event]属性——EventCounter是独立类型 - 构造时传入的名称(如
"http-requests-per-second")会成为指标 ID,后续被dotnet-counters识别 - 写入值必须是
double,整数要显式转成(double)count
using System.Diagnostics;
public static class HttpMetrics
{
private static readonly EventSource _source = new EventSource("MyApp.Http");
public static readonly EventCounter RequestsPerSecond = new EventCounter("http-requests-per-second", _source)
{
DisplayName = "HTTP Requests/sec",
DisplayUnits = "req/s"
};
// 在请求入口处调用
public static void RecordRequest() => RequestsPerSecond.WriteMetric(1.0);
}
dotnet-counters 怎么实时看到指标?常见连不上原因
dotnet-counters 是官方命令行工具,直接消费 EventCounter 数据流,无需修改代码即可启用监控。
- 启动方式:
dotnet-counters monitor --process-id <pid></pid>,默认只显示内置计数器(如system.runtime) - 要看到自定义指标,必须加
--counters参数:dotnet-counters monitor --process-id 12345 --counters MyApp.Http - 连不上常见原因:
- 进程已退出或未启用 EventPipe(.NET 5+ 默认启用,但某些容器环境可能被禁用)
- 权限不足:Linux 上需确保用户有
perf_event_open权限(常需sudo或加入perf组) - 目标进程是 .NET Core 3.1 或更早版本——
EventCounter在 .NET 5 才真正稳定跨平台
生产环境指标导出到 Prometheus 的关键跳板
本地 dotnet-counters 只适合调试。生产环境需要把 EventCounter 数据暴露为 /metrics HTTP 端点供 Prometheus 抓取——这必须靠中间层桥接。
- 推荐方案:
Microsoft.Extensions.Hosting+prometheus-net.DotNetRuntime(轻量,无额外依赖) - 不要自己手写 HTTP handler 暴露指标:格式(文本协议)、采样频率、多实例冲突、Gauge/Counter 类型语义都极易出错
- 关键配置项:
AddDotNetRuntimeMetrics()自动注册 GC/CPU/线程等基础指标;自定义指标需手动映射到ICollectorRegistry - 容易忽略的坑:Prometheus 默认每 15s 抓一次,而
EventCounter是瞬时值,必须用Counter类型累加,不能用Gauge直接写当前请求数











