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

OpenTelemetry .NET自定义子Trace未在Grafana中显示问题求助

问题排查与解决方案

核心问题分析

自定义子Trace未被采集的关键原因有两点:

  • 自定义Activity启动后未正确结束,OpenTelemetry不会采集未完成的Activity
  • 虽配置了AddSource("*"),但Activity生命周期管理缺失导致无法被正常上报

步骤1:修正自定义Activity的生命周期管理

修改WeatherForecastController代码,通过using语句自动完成Activity的启动与结束(或手动调用Stop()):

[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
    internal static readonly ActivitySource activitySource = new(typeof(WeatherForecastController).Namespace ?? "");
    [HttpGet]
    public async Task<ActionResult> Get()
    {
        var root = Activity.Current;
        root?.SetTag("Test", "TestOpenTelemetry");
        
        // 使用using自动管理Activity生命周期,确保结束时被采集
        using var act = activitySource.CreateActivity("subactivity 1", ActivityKind.Client);
        if (act is not null)
        {
            act.Start();
            act.SetTag("Sub", "TestOpenTelemetry Sub");
        }
        
        return Ok();
    }
}

步骤2:确认ActivitySource名称匹配(可选但推荐)

虽然AddSource("*")会匹配所有ActivitySource,但明确指定自定义源名称能避免潜在的匹配问题。假设WeatherForecastController的命名空间为YourAppNamespace.WeatherForecast,修改Startup配置:

builder.Services.AddOpenTelemetry()
    .WithTracing(x =>
    {
        x.AddSource("YourAppNamespace.WeatherForecast")
          .AddSource("TesteOpenTelemetry")
          .AddSource(typeof(Program).Namespace + "*");
          
        x.SetResourceBuilder(ResourceBuilder.CreateDefault()
            .AddService("TesteOpenTelemetry")
            .AddTelemetrySdk());
            
        x.AddAspNetCoreInstrumentation(instrumentationOptions =>
        {
            instrumentationOptions.RecordException = true;
        });
        
        x.AddOtlpExporter(options => 
        {
            options.Endpoint = new Uri("http://127.0.0.1:4317");
        });
    });

步骤3:确保父Activity关联(异常场景处理)

如果遇到子Activity无法关联父Trace的情况,可显式指定父Activity上下文:

using var act = activitySource.CreateActivity("subactivity 1", ActivityKind.Client, root?.Context);

验证操作

启动应用后调用WeatherForecast的Get接口,再查看Grafana Trace面板,此时根Trace下应能看到嵌套的subactivity 1子Trace。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.08 03:23:28