Brad
Brad

Reputation: 10670

OpenTelemetry .NET StartActiveSpan does not do anything while built-in spans are working

I'm following the instructions here to add OpenTelemetry tracing into my web app. I'm calling AddAspNetCoreInstrumentation and AddEntityFrameworkCoreInstrumentation, both which seem to be working; I can see the HTTP handler and database level spans in my Trace (Using Google Cloud Trace View). However, when I try to create a trace span manually with tracer.StartActiveSpan("my-span");, the span is not visible in the trace anywhere.

Here is my configuration code:

var serviceName = Environment.GetEnvironmentVariable("K_SERVICE") ?? "web-ui";

builder.Services.AddOpenTelemetry()
    .ConfigureResource(resource => resource.AddService(serviceName))
    .WithTracing(
        tracing =>
        {
            tracing
                .AddAspNetCoreInstrumentation()
                .AddEntityFrameworkCoreInstrumentation(
                    e =>
                    {
                        e.EnrichWithIDbCommand = (activity, command) =>
                        {
                            var tag = string.Empty;
                            if (command.CommandText.StartsWith("--"))
                            {
                                using var reader = new StringReader(command.CommandText);
                                tag = reader.ReadLine()?[3..];
                            }

                            if (!string.IsNullOrEmpty(tag))
                            {
                                activity.SetTag("db.query.tag", tag);
                            }
                            else
                            {
                                // Store the whole query for non-tagged queries.
                                activity.SetTag("db.query.command", command.CommandText);
                            }
                        };
                    });
            if (configuration.GetSection("Otlp").Exists())
            {
                tracing.AddOtlpExporter(e => configuration.GetSection("Otlp").Bind(e));
            }
        })
    .WithMetrics(
        metrics =>
        {
            metrics
                .AddAspNetCoreInstrumentation();
            if (configuration.GetSection("Otlp").Exists())
            {
                metrics.AddOtlpExporter(e => configuration.GetSection("Otlp").Bind(e));
            }
        });
builder.Services.AddSingleton(TracerProvider.Default.GetTracer(serviceName));

Here is my code to create a span (tracer is injected into the class):

using var span = tracer.StartActiveSpan(nameof(CreateMarkdownComment));

Upvotes: 1

Views: 691

Answers (1)

Brad
Brad

Reputation: 10670

I was missing some configuration lines:

tracing
 .AddSource(serviceName)
 .SetResourceBuilder(
     ResourceBuilder.CreateDefault()
         .AddService(serviceName: serviceName))

Adding these seemed to fix the issue.

Upvotes: 1

Related Questions