You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

.NET类库如何同时支持Prometheus与Application Insights的指标和追踪?

解决方案:用.NET标准诊断API + OpenTelemetry 实现多采集器适配

你可以通过**.NET标准的System.Diagnostics.Metrics和System.Diagnostics.Activity API配合OpenTelemetry**实现需求:类库只写一套标准API代码,宿主应用通过OpenTelemetry配置同时导出指标和追踪数据到Prometheus与Application Insights。

核心逻辑是:.NET标准诊断API是上层抽象,OpenTelemetry可以接收这些标准数据,再通过官方导出器转发到Prometheus和Application Insights,完全不需要为不同采集器编写两套业务代码。


步骤1:类库中使用标准诊断API

类库只依赖.NET原生的诊断组件,不耦合任何采集器实现,保持独立性。

using System.Diagnostics;
using System.Diagnostics.Metrics;

public class CookieService{
    private readonly ICookieRepository _cookieRepository;
    
    // 定义全局Meter(指标)和ActivitySource(追踪),用类库唯一标识命名
    private static readonly Meter _cookieMeter = new Meter("YourCompany.InternalLib.CookieService");
    private static readonly ActivitySource _cookieActivitySource = new ActivitySource("YourCompany.InternalLib.CookieService");
    
    // 预定义所需指标:Counter(计数)、Histogram(耗时分布)、UpDownCounter(模拟Gauge)
    private readonly Counter<long> _cookieAddedCounter = _cookieMeter.CreateCounter<long>(
        "cookies.added.total", 
        description: "Total number of cookies added successfully");
    private readonly Histogram<double> _addCookieDurationHistogram = _cookieMeter.CreateHistogram<double>(
        "cookies.add.duration", 
        unit: "seconds", 
        description: "Duration of cookie add operations");
    private readonly UpDownCounter<long> _pendingAddRequests = _cookieMeter.CreateUpDownCounter<long>(
        "cookies.add.pending", 
        description: "Number of in-progress cookie add requests");

    public CookieService(ICookieRepository cookieRepository){
        _cookieRepository = cookieRepository;
    }

    public async Task AddCookies(CookieDto dto){ 
        var flavorTags = new KeyValuePair<string, object>[] { new("cookie.flavor", dto.Flavor) };
        
        // 更新Gauge类指标:增加待处理请求数
        _pendingAddRequests.Add(1, flavorTags);
        
        // 启动追踪Span
        using var activity = _cookieActivitySource.StartActivity("AddCookies", ActivityKind.Internal);
        activity?.SetTag("cookie.flavor", dto.Flavor);

        var stopwatch = Stopwatch.StartNew();
        try{
            await _cookieRepository.Add(dto);
            // 统计成功添加的Cookie数量
            _cookieAddedCounter.Add(1, flavorTags);
        }
        finally{
            stopwatch.Stop();
            // 记录操作耗时到Histogram
            _addCookieDurationHistogram.Record(stopwatch.Elapsed.TotalSeconds, flavorTags);
            // 更新Gauge类指标:减少待处理请求数
            _pendingAddRequests.Add(-1, flavorTags);
        }
    }
}

步骤2:宿主应用配置OpenTelemetry导出器

在使用类库的宿主应用(比如ASP.NET Core)中,通过OpenTelemetry配置同时导出数据到Prometheus和Application Insights。

所需NuGet包

<PackageReference Include="OpenTelemetry.Exporter.Prometheus.AspNetCore" Version="1.6.0" />
<PackageReference Include="OpenTelemetry.Exporter.AzureMonitor" Version="1.6.0" />
<PackageReference Include="OpenTelemetry.Extensions.Hosting" Version="1.6.0" />

宿主配置代码(ASP.NET Core)

using OpenTelemetry.Metrics;
using OpenTelemetry.Trace;

var builder = WebApplication.CreateBuilder(args);

// 配置OpenTelemetry
builder.Services.AddOpenTelemetry()
    // 配置指标导出
    .WithMetrics(metrics => metrics
        // 启用类库中定义的Meter
        .AddMeter("YourCompany.InternalLib.CookieService")
        // 导出到Prometheus
        .AddPrometheusExporter()
        // 导出到Application Insights
        .AddAzureMonitorMetricExporter(options => {
            options.ConnectionString = builder.Configuration["ApplicationInsights:ConnectionString"];
        }))
    // 配置追踪导出
    .WithTracing(tracing => tracing
        // 启用类库中定义的ActivitySource
        .AddSource("YourCompany.InternalLib.CookieService")
        // 导出到Application Insights
        .AddAzureMonitorTraceExporter(options => {
            options.ConnectionString = builder.Configuration["ApplicationInsights:ConnectionString"];
        }));

// 启用Prometheus指标采集端点
app.UsePrometheusScrapingEndpoint();

// 其他宿主配置...
var app = builder.Build();
app.Run();

关键优势

  1. 无重复代码:类库只使用.NET标准API,完全不关心底层采集器实现。
  2. 官方支持:Application Insights和Prometheus的OpenTelemetry导出器均为官方维护,稳定性有保障。
  3. 扩展性强:后续如需添加其他采集器(如Jaeger、Datadog),仅需在宿主中新增导出器配置,类库无需修改。

内容的提问来源于stack exchange,提问作者atotalnoob

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 11:08:00