启用.NET指标收集后,dotnet-counters无法检测到指标的解决问询
.NET指标无法被dotnet-counters检测到的解决方法
我参考微软官方文档实现了.NET指标收集功能,程序能正常输出指标数据,但使用dotnet-counters时找不到对应进程,无法查看指标。请问如何让指标被dotnet-counters检测到?
编译运行的程序代码
using System; using System.Collections.Generic; using System.Diagnostics.Metrics; using System.Threading; namespace ConsoleApp7 { internal class Program { static void Main(string[] args) { Meter s_meter = new("HatCo.HatStore", "1.0.0"); Counter<int> s_hatsSold = s_meter.CreateCounter<int>("hats-sold"); using MeterListener meterListener = new(); meterListener.InstrumentPublished = (instrument, listener) => { if (instrument.Meter.Name is "HatCo.HatStore") { listener.EnableMeasurementEvents(instrument); } }; meterListener.SetMeasurementEventCallback<int>(OnMeasurementRecorded); // Start the meterListener, enabling InstrumentPublished callbacks. meterListener.Start(); var rand = Random.Shared; Console.WriteLine("Press any key to exit"); while (!Console.KeyAvailable) { //// Simulate hat selling transactions. Thread.Sleep(rand.Next(100, 2500)); s_hatsSold.Add(rand.Next(0, 1000)); } static void OnMeasurementRecorded<T>( Instrument instrument, T measurement, ReadOnlySpan<KeyValuePair<string, object?>> tags, object? state) { Console.WriteLine($"{instrument.Name} recorded measurement {measurement}"); } } } }
程序输出窗口显示
hats-sold recorded measurement 253 hats-sold recorded measurement 168 hats-sold recorded measurement 473 hats-sold recorded measurement 790
dotnet-counters命令执行结果
C:\Users\me>dotnet-counters monitor -n metric-instr There is no active process with the given name: metric-instr
解决步骤
1. 确认进程名称或PID正确性
你用的进程名metric-instr和实际程序进程名不匹配——你的程序命名空间是ConsoleApp7,默认编译后进程名应为ConsoleApp7.exe(Windows)或ConsoleApp7(Linux/macOS)。可以通过以下方式获取正确进程信息:
- 执行
dotnet-counters list命令,查看所有可监控的.NET进程,找到目标程序的进程名或PID - 用任务管理器(Windows)或
ps命令(Linux/macOS)查看进程真实名称
2. 使用正确的命令格式
用匹配的进程名执行命令:
dotnet-counters monitor -n ConsoleApp7 --counters HatCo.HatStore
或用PID更可靠:
dotnet-counters monitor -p <进程PID> --counters HatCo.HatStore
3. 精确指定计数器
如果需要查看单个指标,可直接指定Meter和指标名称:
dotnet-counters monitor -n ConsoleApp7 --counters HatCo.HatStore/hats-sold
4. 检查.NET版本兼容性
确保dotnet-counters工具版本和目标程序运行的.NET版本兼容(例如.NET 6+程序需对应版本的dotnet-counters)
5. 移除自定义MeterListener(可选)
代码中的自定义MeterListener仅用于本地打印指标,不影响dotnet-counters的采集——dotnet-counters通过系统Metrics管道直接获取数据,无需额外配置Listener。如果不需要本地打印,可移除这段代码避免混淆
内容的提问来源于stack exchange,提问作者junkone
相关产品推荐
相关产品推荐

