skip to content

OpenTelemetry Traces & Metrics

AddOpenTelemetry hooks tracing and metrics to ASP.NET Core's built-in activities and meters, adds custom spans and exports over OTLP. Interviewers probe what is native and what needs packages.

part ofASP.NET Coreread it →
on this pageshow

explore

questions

6

In ASP.NET Core 10, how do you send traces, metrics and logs to an OTLP collector with AddOpenTelemetry, and which packages does that need?

level: middleimportance: must knowfreq 62%

answer

  1. one builder, three With* calls
  2. OpenTelemetry.Extensions.Hosting
  3. AddAspNetCoreInstrumentation on both builders
  4. UseOtlpExporter once, all signals
  5. gRPC on localhost:4317 by default

basics

~10 s

Call builder.Services.AddOpenTelemetry(), chain WithTracing and WithMetrics with AddAspNetCoreInstrumentation plus your AddSource/AddMeter names, add WithLogging, then UseOtlpExporter(). Packages: OpenTelemetry.Extensions.Hosting, OpenTelemetry.Instrumentation.AspNetCore and OpenTelemetry.Exporter.OpenTelemetryProtocol.

solid answer

~30 s

I add three packages: `OpenTelemetry.Extensions.Hosting` for `AddOpenTelemetry()`, `OpenTelemetry.Instrumentation.AspNetCore` for `AddAspNetCoreInstrumentation()`, and `OpenTelemetry.Exporter.OpenTelemetryProtocol` for the OTLP exporter, plus `OpenTelemetry.Instrumentation.Http` if outgoing calls should join the trace. In `Program.cs` I call `builder.Services.AddOpenTelemetry()`, name the service with `ConfigureResource`, then `.WithTracing(t => t.AddAspNetCoreInstrumentation().AddHttpClientInstrumentation().AddSource("Airline.Booking"))`, `.WithMetrics(m => m.AddAspNetCoreInstrumentation().AddMeter("Airline.Booking"))` and `.WithLogging()`. Finally `.UseOtlpExporter()` registers one exporter for all three signals; it reads `OTEL_EXPORTER_OTLP_ENDPOINT` and otherwise defaults to gRPC at `http://localhost:4317` on .NET 10. It may be called once and cannot be mixed with per-signal `AddOtlpExporter` calls, which fail with `NotSupportedException`. OpenTelemetry 1.19 also adds `builder.AddOpenTelemetry()` on the host builder.

code

csharp · 19 lines
csharp
using OpenTelemetry.Metrics;
using OpenTelemetry.Resources;
using OpenTelemetry.Trace;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddOpenTelemetry()
    .ConfigureResource(r => r.AddService("booking-api"))
    .WithTracing(t => t
        .AddAspNetCoreInstrumentation()
        .AddHttpClientInstrumentation()
        .AddSource("Airline.Booking"))
    .WithMetrics(m => m
        .AddAspNetCoreInstrumentation()
        .AddMeter("Airline.Booking"))
    .WithLogging()
    .UseOtlpExporter(); // one exporter, all three signals

var app = builder.Build();

go deeper

for a junior

Know that AddOpenTelemetry lives in OpenTelemetry.Extensions.Hosting and that tracing and metrics are configured separately with WithTracing and WithMetrics.

for a middle

Walk through the full Program.cs: resource name, both instrumentation calls, AddSource and AddMeter for custom code, WithLogging, and why UseOtlpExporter is called once.

for a senior

Explain the exporter rules: environment-driven endpoints, gRPC on 4317 versus HTTP/protobuf on 4318, the NotSupportedException when mixing UseOtlpExporter with AddOtlpExporter, and when per-signal exporters are justified.

for a principal

Decide where the shared wiring lives across many services, and how to roll out exporter or endpoint changes without editing every service's Program.cs.

## The scenario An airline's checkout touches three ASP.NET Core 10 services: **booking-api** takes the order, **seat-inventory** holds the seat, **payments** charges the card. Each one should send its traces, metrics and logs to an OpenTelemetry Collector over **OTLP** (the OpenTelemetry Protocol), so one trace can show the whole checkout and dashboards can read request rates and latencies. ## The packages | Package | What it provides | |---|---| | `OpenTelemetry.Extensions.Hosting` | `AddOpenTelemetry()`, the `OpenTelemetryBuilder` with `WithTracing`, `WithMetrics`, `WithLogging`, `ConfigureResource`, and provider shutdown with the host | | `OpenTelemetry.Instrumentation.AspNetCore` | `AddAspNetCoreInstrumentation()` on the tracer and meter builders | | `OpenTelemetry.Instrumentation.Http` | `AddHttpClientInstrumentation()` so outgoing `HttpClient` calls appear as client spans | | `OpenTelemetry.Exporter.OpenTelemetryProtocol` | `UseOtlpExporter()` and the per-signal `AddOtlpExporter()` | `OpenTelemetry.Exporter.Console` is a handy extra while developing; it prints telemetry to standard output. ## The wiring, step by step 1. **Create the builder.** `builder.Services.AddOpenTelemetry()` returns an `OpenTelemetryBuilder`. OpenTelemetry .NET **1.19.0** added an overload on `IHostApplicationBuilder`, so `builder.AddOpenTelemetry()` also works; it seeds `service.name` from the environment's `ApplicationName` and `deployment.environment.name` from `EnvironmentName` as low-priority defaults. 2. **Name the service.** `ConfigureResource(r => r.AddService("booking-api"))` sets the resource every signal carries; without a name the backend groups data under a placeholder. 3. **Traces.** `WithTracing(t => ...)` builds a tracer provider. `AddAspNetCoreInstrumentation()` subscribes to the incoming-request activity, `AddHttpClientInstrumentation()` to outgoing calls, and `AddSource("Airline.Booking")` to your own `ActivitySource`. 4. **Metrics.** `WithMetrics(m => ...)` builds a meter provider. `AddAspNetCoreInstrumentation()` subscribes to ASP.NET Core's built-in meters, and `AddMeter("Airline.Booking")` to your own meter. 5. **Logs.** `WithLogging()` adds an OpenTelemetry provider behind `ILogger`. Each record it captures carries the trace and span id of `Activity.Current`, which is what lets a log line jump to its trace. 6. **Export.** `UseOtlpExporter()` adds one OTLP exporter for all three signals. ## How the three services fit together Each of the three services carries the same block with a different `AddService` name: `booking-api`, `seat-inventory`, `payments`. That symmetry is what makes the checkout readable end to end: - **Traces.** booking-api's request span is the root. Its outgoing `HttpClient` calls produce client spans, and the receiving services' hosting layers continue the same trace, so seat-inventory's and payments' request spans appear as children in one tree. - **Metrics.** Every service exports `http.server.request.duration` from the built-in hosting meter, tagged with `http.route` and the status code, plus any custom meter it subscribes to. The resource's service name separates the three in dashboards. - **Logs.** Each service's log records carry the trace id of the request they were written in, so a failed payment's error log links to the same trace as the booking that triggered it. A common refactor is to move this block into a shared extension method, for example `AddAirlineTelemetry(this IHostApplicationBuilder builder, string serviceName)`, so the three services cannot drift apart. ## The rules of `UseOtlpExporter` - Calling it **automatically enables** logging, metrics and tracing, and the exporter is added as the last processor in the logging and tracing pipelines. - It may be called **once**; a second call on the same service collection throws `NotSupportedException` when the providers are built. - It **cannot be combined** with the signal-specific `AddOtlpExporter()` methods; doing both also throws `NotSupportedException`. Use `AddOtlpExporter` inside `WithTracing` or `WithMetrics` only when signals must go to different endpoints. - With no configuration it reads the standard `OTEL_EXPORTER_OTLP_*` environment variables. Without them, on modern .NET it uses **gRPC** at `http://localhost:4317`; HTTP/protobuf (`OtlpExportProtocol.HttpProtobuf`) defaults to `http://localhost:4318`. On .NET Framework the library defaults to HTTP/protobuf instead, which is why a docs page claiming "gRPC everywhere" is incomplete. - The overload `UseOtlpExporter(OtlpExportProtocol protocol, Uri baseUrl)` sets both in code; with HTTP/protobuf it appends each signal's path to the base URL. ## Where this lands in `Program.cs` The call belongs with the other service registrations, before `builder.Build()`. Nothing is added to the middleware pipeline: the request activity and metrics come from the hosting layer, so there is no OpenTelemetry middleware to add or order. ## Checking it works - Temporarily add `AddConsoleExporter()` (console package) to see spans locally. - Point `OTEL_EXPORTER_OTLP_ENDPOINT` at the collector in each environment instead of hard-coding the URL. - If custom spans are missing, compare the `AddSource` name with the `ActivitySource` name character by character; wildcards such as `Airline.*` are accepted. ## Version notes This answer assumes ASP.NET Core 10 with OpenTelemetry .NET 1.19 and OpenTelemetry.Instrumentation.AspNetCore 1.19.0. `UseOtlpExporter` and `WithLogging` exist in earlier 1.x releases; the `IHostApplicationBuilder` overload is the 1.19.0 addition.

  • Traces must go to one collector and metrics to another. How do you configure that?
    Drop `UseOtlpExporter()` and call `AddOtlpExporter(o => o.Endpoint = new Uri(...))` inside `WithTracing` and inside `WithMetrics` separately. The two styles cannot be mixed: once `UseOtlpExporter` is registered, any signal-specific `AddOtlpExporter` makes provider construction throw `NotSupportedException`.
  • Why do the logs now carry trace ids without any code change?
    `WithLogging` puts an OpenTelemetry logger provider behind `ILogger`. When a log call happens inside a request, the provider reads `Activity.Current` and copies its trace id and span id onto the log record, so the backend can link the line to the request's trace.
  • Is there any middleware to add for OpenTelemetry, and where would it go?
    No. ASP.NET Core's hosting layer starts the request activity and records request metrics before any middleware runs, and the SDK subscribes to them as a listener. Everything is service registration on the builder; nothing is added with a `Use...` call on `app`.

  • Request spans need a tracing middleware registered with app.UseMiddleware first.
  • UseOtlpExporter() can be combined with AddOtlpExporter() inside WithTracing for extra control.
  • The OTLP exporter defaults to HTTP on port 4318 on .NET 10.
  • AddAspNetCoreInstrumentation() on the tracer builder also turns on the request metrics.
  • WithLogging() replaces ILogger, so log calls must change to an OpenTelemetry API.

Assumes ASP.NET Core 10 with OpenTelemetry .NET 1.19; builder.AddOpenTelemetry() on IHostApplicationBuilder is new in 1.19.0.

open as a page

In .NET, which built-in types carry OpenTelemetry traces, metrics and logs, and what does the OpenTelemetry SDK add on top of them?

level: juniorimportance: should knowfreq 45%

basics

~10 s

.NET records traces with System.Diagnostics.Activity started from an ActivitySource, metrics with a System.Diagnostics.Metrics.Meter and its instruments, and logs with ILogger. The OpenTelemetry SDK adds the listeners, processing and exporters that ship them out.

open as a page

What telemetry does ASP.NET Core 10 produce with no OpenTelemetry package installed, and what does AddAspNetCoreInstrumentation add on top?

level: middleimportance: should knowfreq 42%

basics

~20 s

ASP.NET Core 10 creates a request Activity and, since .NET 8, records metrics such as http.server.request.duration on built-in meters. AddAspNetCoreInstrumentation subscribes the SDK to them, adds span attributes and filter/enrich hooks; exporting still needs the SDK.

open as a page

In an ASP.NET Core 10 checkout that calls seat-inventory and payment services, how do you add a custom span with ActivitySource, and why might it never be exported?

level: seniorimportance: should knowfreq 40%

basics

~20 s

Keep one long-lived ActivitySource, wrap the step in using var activity = source.StartActivity("HoldSeat"), tag via activity?.SetTag, and list the name in AddSource. Spans go missing when the name is unsubscribed, the trace unsampled, or the activity never stopped.

open as a page

Health probes hit /health on your ASP.NET Core 10 booking API every few seconds; how do you keep them out of its request metrics and traces?

level: seniorimportance: should knowfreq 30%

basics

~10 s

Chain .DisableHttpMetrics() on the health endpoint (or put [DisableHttpMetrics] on an action) so ASP.NET Core skips http.server.request.duration, and set AspNetCoreTraceInstrumentationOptions.Filter to drop the path from traces. The two switches are independent.

open as a page

In ASP.NET Core 10, why create a custom bookings metric through IMeterFactory rather than a static Meter, and how does it reach the exporter?

level: seniorimportance: should knowfreq 35%

basics

~20 s

IMeterFactory, registered by the host, creates meters tied to the DI container: cached per name, disposed with the container, and distinguishable per host in tests. A singleton creates the instruments once, and WithMetrics(m => m.AddMeter("Airline.Booking")) exports them.

open as a page