如何通过代码访问.NET Core Event-Counters并发布为指标
访问dotnet-counters可获取的Event-Counter统计数据方法
一、通过dotnet-counters命令行工具直接操作
- 列出所有可用计数器:执行命令
dotnet counters list,会返回已注册的所有计数器类别及下属具体统计项。 - 实时监控指定进程:先通过
dotnet ps获取目标.NET进程的ID,再执行dotnet counters monitor --process-id <进程ID> <计数器类别>,例如监控GC相关数据可运行dotnet counters monitor --process-id 1234 System.Runtime。 - 导出数据到文件:若需要持久化统计结果,使用
dotnet counters collect --process-id <进程ID> --output <输出文件名> <计数器类别>,支持导出为JSON格式便于后续分析。
二、在代码中通过API自定义采集
如果要在应用内部获取这些计数器数据,可借助System.Diagnostics.Tracing命名空间的API实现:
- 确保项目引用
System.Diagnostics.DiagnosticSourceNuGet包(按需添加)。 - 创建
EventListener子类订阅Event-Counter事件:
using System; using System.Collections.Generic; using System.Diagnostics.Tracing; public class CounterCollector : EventListener { protected override void OnEventSourceCreated(EventSource eventSource) { // 订阅目标EventSource,这里以System.Runtime为例 if (eventSource.Name == "System.Runtime") { EnableEvents(eventSource, EventLevel.Informational, EventKeywords.All, new Dictionary<string, string> { ["EventCounterIntervalSec"] = "1" // 设置采集间隔为1秒 }); } } protected override void OnEventWritten(EventWrittenEventArgs eventData) { if (eventData.EventName == "EventCounters") { foreach (var payloadItem in eventData.Payload) { if (payloadItem is IDictionary<string, object> counterInfo) { string counterName = counterInfo["Name"].ToString(); // 根据计数器类型选择取值字段,如Mean、Count、Increment等 float counterValue = (float)counterInfo["Mean"]; Console.WriteLine($"[{DateTime.Now}] {counterName}: {counterValue}"); } } } } }
- 在应用启动时实例化该类,即可实时接收并处理计数器数据。
三、借助第三方监控工具采集
主流APM工具(如Prometheus搭配.NET exporter、Datadog等)大多内置了对这些Event-Counter的支持,只需简单配置就能自动采集、展示并分析这些统计指标。
内容的提问来源于stack exchange,提问作者Mehrdad
相关产品推荐
相关产品推荐

