Search code examples
asp.net-coregrafanaopen-telemetryopen-telemetry-collector

Open telemetry .NET I can't make my trace to show under the controller trace


I created this controller

`C#

[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");
        var act = activitySource.CreateActivity("subactivity 1", ActivityKind.Client);
        act?.Start();
        act?.SetTag("Sub", "TestOpenTelemetry Sub");
        return Ok();
    }
}

`

and put this code on my startup

`C# var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
builder.Services.AddOpenTelemetry()
.WithTracing
(x =>
{
   x.AddSource("TesteOpenTelemetry").AddSource(typeof(Program).Namespace + "*").AddSource("*");
   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"));
 });
 var app = builder.Build();

 // Configure the HTTP request pipeline.

 app.UseHttpsRedirection();

 app.UseAuthorization();


 app.MapControllers();

 app.Run();`

but when I open the trace on grafana I get just the parent trace

grafana parent trace

I was expecting to show the parent trace and the child trace inside them

I tried many ways to add the source, just each one, all of them, groups C# x.AddSource("TesteOpenTelemetry").AddSource(typeof(Program).Namespace + "*").AddSource("*");

and nothing seems to work, EF core traces appear, http client traces also work, but my traces don't appear on my grafana


Solution

  • Make sure you call Activity.Stop, otherwise your activity never ends and never gets exported:

    var act = activitySource.CreateActivity("subactivity 1", ActivityKind.Client);
    act?.Start();
    act?.Stop();
    

    Alternatively, make sure the activity is disposed at the end of the scope:

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