如何将System.Diagnostics.Metrics指标接入Application Insights?
将System.Diagnostics.Metrics指标纳入Application Insights
你说得没错,2.22.0版本的Microsoft.ApplicationInsights.AspNetCore SDK仅原生支持EventCounter,无法直接采集System.Diagnostics.Metrics(OpenTelemetry Metrics标准)生成的指标。下面提供两种可行的解决方案:
方案1:升级SDK到支持Metrics的版本
从2.24.0版本开始,Application Insights ASP.NET Core SDK加入了对System.Diagnostics.Metrics的原生支持(2.21.0起有初步支持,但2.24.0+稳定性更好)。只需更新你的包引用:
<PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.24.0" /> <!-- 建议使用最新稳定版 -->
升级完成后,无需额外配置EventCounterCollectionModule,SDK会自动采集所有通过Meter创建的指标(包括你定义的mycounter)。默认配置下不会过滤指标,若需自定义采集规则,可通过ApplicationInsightsServiceOptions调整。
方案2:自定义Metrics监听器(适用于无法升级SDK的场景)
如果无法升级SDK,可通过MeterListener手动监听Metrics数据,再推送到Application Insights:
步骤1:创建自定义监听器类
using System.Diagnostics.Metrics; using Microsoft.ApplicationInsights; using Microsoft.ApplicationInsights.DataContracts; public class CustomMetricsListener : IDisposable { private readonly MeterListener _listener; private readonly TelemetryClient _telemetryClient; public CustomMetricsListener(TelemetryClient telemetryClient) { _telemetryClient = telemetryClient; _listener = new MeterListener(); // 监听目标Meter(这里匹配你的"My.App") _listener.InstrumentPublished = (instrument, listener) => { if (instrument.Meter.Name == MyMetrics.Name) { listener.EnableMeasurementEvents(instrument); } }; // 处理Counter类型的指标(int类型) _listener.SetMeasurementEventCallback<int>((instrument, measurement, tags, state) => { var metricTelemetry = new MetricTelemetry(instrument.Name, measurement); // 附加指标标签作为AI自定义属性 foreach (var tag in tags) { metricTelemetry.Properties[tag.Key] = tag.Value.ToString(); } _telemetryClient.TrackMetric(metricTelemetry); }); _listener.Start(); } public void Dispose() { _listener.Dispose(); } }
步骤2:注册监听器
在Program.cs(.NET 6+)或Startup.cs中注册该监听器为单例:
// .NET 6+ Program.cs builder.Services.AddSingleton<CustomMetricsListener>(); // 旧版Startup.cs ConfigureServices方法 services.AddSingleton<CustomMetricsListener>();
当你的CountMe()方法触发计数器增量时,监听器会捕获数据并通过TelemetryClient发送到Application Insights。
扩展说明
- 上述示例仅处理了
int类型的Counter,若需支持Gauge、Histogram等其他指标类型,可添加对应类型的SetMeasurementEventCallback重载。 - 可根据需求调整
InstrumentPublished逻辑,实现更精细的指标过滤。
内容的提问来源于stack exchange,提问作者mortenbock
相关产品推荐
相关产品推荐

