LESSON 9 OF 12

9. OpenTelemetry Fundamentals and ASP.NET Core Tracing

Learn OpenTelemetry architecture, Activity and Resource concepts, and automatic span generation for ASP.NET Core and HttpClient calls.

45 dk 68

Introduction

In the previous lessons, we covered log levels, request logging, correlation IDs, and global exception handling. This lesson moves beyond logs and shows how to follow an HTTP request from the moment it enters an application until it calls an external service. This capability is known as distributed tracing.

OpenTelemetry is an ecosystem based on open standards for collecting traces, metrics, and logs from applications. Although this lesson focuses on tracing, the same architecture can later be extended to metrics and logs. In ASP.NET Core, the goal is to create spans automatically through official instrumentation components instead of adding manual timing code to every controller action.

By the end of the lesson, the application will create server spans for incoming HTTP requests, client spans for outbound HttpClient calls, and send the resulting telemetry through OTLP to an observability backend.

Core OpenTelemetry concepts

Activity and span

In the .NET ecosystem, Activity is the equivalent of an OpenTelemetry span. An Activity contains an operation name, start time, duration, kind, status, attributes, and trace relationships. Activities belonging to the same trace are connected through parent-child relationships.

ActivitySource is the source used to create Activities. When adding manual instrumentation, a meaningful unit of work can be wrapped with an Activity:

using System.Diagnostics;

public static class OrderTelemetry
{
    public static readonly ActivitySource Source =
        new("ObservabilityDemo.Orders");

    public static async Task ProcessAsync()
    {
        using Activity? activity = Source.StartActivity("process-order");
        await Task.Delay(50);
        activity?.SetTag("order.type", "standard");
    }
}

StartActivity can return null when no listener or tracer provider is interested in the source. For that reason, manual Activity usage should be null-safe. This behavior is a performance optimization that avoids unnecessary object creation when telemetry is disabled or not collected.

Resource and service.name

A Resource contains stable identity information about the service producing telemetry. Service name, version, deployment environment, and service instance are typical resource attributes. Without service.name, it becomes difficult to distinguish services running in the same environment.

Choose a meaningful and stable name for every service, such as orders-api, catalog-api, or checkout-worker. Values that vary by deployment should be represented separately, for example with the deployment.environment resource attribute.

Instrumentation

Instrumentation observes operations inside a framework or library automatically. AddAspNetCoreInstrumentation observes incoming ASP.NET Core requests, while AddHttpClientInstrumentation observes outbound calls made through HttpClient.

This means you do not need to add a manual Activity to every controller method. A server span is created for an incoming request and a client span for an outbound call. HttpClient instrumentation also helps propagate trace context through HTTP headers. If the receiving service is instrumented as well, both spans can appear under the same trace.

Exporter and OTLP

An exporter transports collected telemetry to a selected destination. The Console Exporter is convenient during development. In production, OTLP is a common option for sending telemetry to the OpenTelemetry Collector, Jaeger, or another compatible backend.

OTLP stands for OpenTelemetry Protocol. It can transport data over HTTP or gRPC. This lesson uses a gRPC-style endpoint such as http://localhost:4317. The endpoint must actually be listening; otherwise spans may be created locally while the exporter reports delivery failures.

Sampling

Sampling determines which traces are recorded and exported. AlwaysOnSampler samples every trace and is useful for local testing because results are easy to see. In production, recording every request can create significant data volume and cost.

ParentBasedSampler respects the decision made by an existing parent trace. When there is no parent, it uses a configured root sampler. In distributed systems, sampling policies should be designed consistently so that services do not make conflicting decisions for the same trace.

Adding the packages

From the directory containing the ASP.NET Core Web API project, add the following packages:

dotnet add package OpenTelemetry.Extensions.Hosting
dotnet add package OpenTelemetry.Instrumentation.AspNetCore
dotnet add package OpenTelemetry.Instrumentation.Http
dotnet add package OpenTelemetry.Exporter.OpenTelemetryProtocol
dotnet add package OpenTelemetry.Exporter.Console

Keep the package versions within the same OpenTelemetry release family. Use current stable versions compatible with the target .NET version of your project. The examples intentionally do not pin a version so that package selection can follow your organization's NuGet and security policies.

Configuring tracing in ASP.NET Core

The following example targets the minimal hosting model and can be placed in Program.cs:

using OpenTelemetry.Resources;
using OpenTelemetry.Trace;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddHttpClient();
builder.Services.AddControllers();

builder.Services.AddOpenTelemetry()
    .ConfigureResource(resource => resource
        .AddService(
            serviceName: "orders-api",
            serviceVersion: typeof(Program).Assembly.GetName().Version?.ToString() ?? "unknown",
            serviceInstanceId: Environment.MachineName)
        .AddAttributes(new Dictionary<string, object>
        {
            ["deployment.environment"] = builder.Environment.EnvironmentName
        }))
    .WithTracing(tracing =>
    {
        tracing
            .AddAspNetCoreInstrumentation(options =>
            {
                options.Filter = httpContext =>
                    !httpContext.Request.Path.StartsWithSegments("/health");
            })
            .AddHttpClientInstrumentation()
            .SetSampler(new ParentBasedSampler(new AlwaysOnSampler()))
            .AddOtlpExporter(options =>
            {
                options.Endpoint = new Uri(
                    builder.Configuration["OTEL_EXPORTER_OTLP_ENDPOINT"]
                    ?? "http://localhost:4317");
            });
    });

var app = builder.Build();

app.MapControllers();
app.MapGet("/health", () => Results.Ok(new { status = "ok" }));

app.Run();

AddAspNetCoreInstrumentation automatically observes incoming HTTP requests. Filtering health endpoints can reduce trace volume from continuously running probes. Do not apply the filter blindly: if health-check failures are important to your investigation workflow, you may prefer to keep them in the trace stream.

AddHttpClientInstrumentation creates client spans for supported HttpClient call flows. You should still use named or typed HttpClient instances because they centralize endpoint, timeout, and resilience configuration.

Tracing an HttpClient call

For example, a controller can call an external catalog service:

[ApiController]
[Route("api/orders")]
public sealed class OrdersController : ControllerBase
{
    private readonly IHttpClientFactory _httpClientFactory;

    public OrdersController(IHttpClientFactory httpClientFactory)
    {
        _httpClientFactory = httpClientFactory;
    }

    [HttpGet("{id:int}")]
    public async Task<IActionResult> Get(int id, CancellationToken cancellationToken)
    {
        HttpClient client = _httpClientFactory.CreateClient();
        using HttpResponseMessage response = await client.GetAsync(
            $"https://api.example.test/catalog/{id}",
            cancellationToken);

        if (!response.IsSuccessStatusCode)
        {
            return StatusCode((int)response.StatusCode);
        }

        string content = await response.Content.ReadAsStringAsync(cancellationToken);
        return Ok(new { id, catalog = content });
    }
}

During this operation, you should typically see a server span with a child client span. The domain in the example is illustrative only. For a working test, use a mock service or a second local API that your application can reach.

Managing Resource values with environment variables

Although service identity can be configured in code, environment variables are often more flexible in deployment environments:

OTEL_SERVICE_NAME=orders-api
OTEL_RESOURCE_ATTRIBUTES=deployment.environment=staging,team=payments
OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4317

OTEL_SERVICE_NAME sets the service.name resource attribute. If the same attribute is also supplied through OTEL_RESOURCE_ATTRIBUTES, the explicit service-name setting should take precedence. Make sure that code-based and environment-based configuration do not unintentionally disagree.

Changing the sampling policy

To see every trace during local testing, use:

.SetSampler(new AlwaysOnSampler())

For a parent-based ratio sampler, use:

.SetSampler(new ParentBasedSampler(new TraceIdRatioBasedSampler(0.10)))

This configuration targets approximately 10 percent of root traces. It is not a fixed daily quota; the decision is made deterministically from the trace ID. Error traces, critical workflows, and slow requests can be handled with more advanced tail-based policies in the Collector.

Testing the configuration

  1. Verify that the OTLP endpoint is running. During a local test, you can temporarily add the Console Exporter to reduce backend dependencies.
  2. Start the application and send a request to an API endpoint.
  3. Search the tracing backend using service.name=orders-api.
  4. Inspect the server span for method, route, status code, and duration.
  5. If the controller calls an external service, verify that a child client span is present.
  6. In a two-service test, confirm that trace context is propagated and that both services use the same trace ID.

If no spans appear, first check the sampler, exporter endpoint, package references, and whether the application actually received a request. Inspecting Activity.Current temporarily inside a controller can also help confirm the active span context.

Common mistakes

  • Using the wrong service name: Giving every service the same name makes trace searches and service maps misleading.
  • Installing but not enabling instrumentation: Adding a NuGet package is not enough; you must call AddAspNetCoreInstrumentation and AddHttpClientInstrumentation.
  • Confusing OTLP ports: gRPC and HTTP/protobuf endpoints may use different protocols or ports. Match exporter settings with the Collector configuration.
  • Leaving AlwaysOn in production: It is useful for development but can generate excessive telemetry volume and cost in production.
  • Recording sensitive data: Do not place tokens, passwords, personal data, or complete query parameters in span attributes.
  • Duplicating automatic spans: Adding manual spans around every operation already covered by instrumentation creates noise and makes traces harder to read.
  • Ignoring health-check traffic: Frequently executed probes can dominate the trace stream. Decide whether to filter them based on your operational needs.

Short practice exercise

Add an /api/orders/{id} endpoint and configure a typed HttpClient that calls a local catalog API. Add deployment.environment and service.version to the resource configuration. First use AlwaysOnSampler and locate one complete trace. Then switch to a 10 percent ratio sampler and observe that some requests are not recorded.

Finally, enable and disable the health endpoint filter and compare the number of traces. You should be able to answer these questions: Which span is the server span? Which attributes does the child client span contain? Why does the trace ID remain the same when one request crosses two services?

Conclusion

OpenTelemetry moves observability beyond a collection of log files toward a standard telemetry model that shows distributed operation flow. Activity and ActivitySource are the fundamental .NET building blocks. Resource data identifies the service, instrumentation creates spans automatically, exporters deliver telemetry, and OTLP provides a portable protocol between the application and backend systems.

With ASP.NET Core and HttpClient instrumentation, incoming requests and outbound calls can be traced with minimal code. In the next stage, these traces can be correlated with metrics and logs so that errors, latency, and service dependencies can be analyzed together.

Sources