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

如何从.NET 8 WinForms应用导出OpenTelemetry追踪数据?

.NET 8 WinForms 对接 Prometheus/Grafana 的 OpenTelemetry 问题

我正在.NET 8 WinForms应用中尝试使用OpenTelemetry,对接Docker环境下的Prometheus与Grafana,基础代码来自《Getting Started with Prometheus and Grafana》文档。

核心问题:

  • 因Windows上会运行多实例应用、不同账户运行会导致端口占用,无法使用Prometheus拉取方式,只能采用推送方式
  • 自定义指标(如MyFruitCounter)能正常在Grafana中看到,但追踪数据无法推送成功
  • 尝试过直接配置OTLP推送到http://localhost:4317,但未生效

现有代码配置

Program.cs 核心初始化代码

[STAThread]
static void Main()
{
    var resourceBuilder = ResourceBuilder.CreateDefault()
        .AddService("WinFormsOpenTelemetryMetrics");

    // 配置追踪
    Sdk.CreateTracerProviderBuilder()
        .SetResourceBuilder(resourceBuilder)
        .AddSource("WinFormsOpenTelemetryActivitySource")
        .AddConsoleExporter()
        .AddOtlpExporter(otlpOptions =>
        {
            otlpOptions.Endpoint = new Uri("http://localhost:9090/api/v1/otlp/v1/traces");
            otlpOptions.Protocol = OtlpExportProtocol.HttpProtobuf;
            otlpOptions.ExportProcessorType = ExportProcessorType.Batch;
        })
        .Build();

    // 配置指标
    Sdk.CreateMeterProviderBuilder()
        .SetResourceBuilder(resourceBuilder)
        .AddMeter("WinFormsOpenTelemetryMeter")
        .AddProcessInstrumentation()
        .AddRuntimeInstrumentation()
        .AddConsoleExporter()
        .AddOtlpExporter((exporterOptions, metricReaderOptions) =>
        {
            exporterOptions.Endpoint = new Uri("http://localhost:9090/api/v1/otlp/v1/metrics");
            exporterOptions.Protocol = OtlpExportProtocol.HttpProtobuf;
            metricReaderOptions.PeriodicExportingMetricReaderOptions.ExportIntervalMilliseconds = 1000;
        })
        .Build();

    ApplicationConfiguration.Initialize();

    var container = Configure();
    using (var scope = container.BeginLifetimeScope())
    {
        Application.Run(scope.Resolve<Form1>());
    }
}

正常工作的指标代码

private static readonly Meter MyMeter = new("WinFormsOpenTelemetryMeter", "1.0");
private static readonly Counter<long> MyFruitCounter = MyMeter.CreateCounter<long>("MyFruitCounter");

private void timer1_Tick(object sender, EventArgs e)
{
    MyFruitCounter.Add(DateTime.Now.Second, new("name", "lemon"), new("color", "yellow"));
}

无法推送的追踪代码

static readonly ActivitySource _sSource = new ActivitySource("WinFormsOpenTelemetryActivitySource");

private async void timerTracing_Tick(object sender, EventArgs e)
{
    using (Activity a = _sSource.StartActivity("SomeWork"))
    {
        await StepOne();
        await StepTwo();
    }
}

static async Task DoSomeWork()
{
    using (Activity a = _sSource.StartActivity("SomeWork"))
    {
        await StepOne();
        await StepTwo();
    }
}

Docker Compose 配置

version: '3.8'
services:
  prometheus:
    image: prom/prometheus:latest
    container_name: prometheus
    command:
      - '--config.file=/etc/prometheus/prometheus.yml'
      - '--enable-feature=otlp-write-receiver'
    volumes:
      - ./prometheus.yml:/etc/prometheus/prometheus.yml
    ports:
      - "9090:9090"
    networks:
      - monitoring
  grafana:
    image: grafana/grafana:latest
    container_name: grafana
    environment:
      - GF_SECURITY_ADMIN_PASSWORD=admin
    ports:
      - "3000:3000"
    volumes:
      - grafana-storage:/var/lib/grafana
    networks:
      - monitoring
  otel-collector:
    image: otel/opentelemetry-collector:latest
    container_name: otel-collector
    command: ["--config=/etc/otel-collector-config.yml"]
    volumes:
      - ./otel-collector-config.yml:/etc/otel-collector-config.yml
    ports:
        - "1888:1888" # pprof extension
        - "8888:8888" # Prometheus metrics exposed by the Collector
        - "8889:8889" # Prometheus exporter metrics
        - "13133:13133" # health_check extension
        - "4317:4317" # OTLP gRPC receiver
        - "4318:4318" # OTLP http receiver
        - "55679:55679" # zpages extension
    networks:
      - monitoring
volumes:
  grafana-storage:
networks:
  monitoring:

疑问

  • 是否可以实现WinForms多实例推送追踪与指标到Docker中的Prometheus?
  • 当前追踪数据无法推送,应该从哪些方向排查问题?

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 17:55:17