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?
answer
- one builder, three With* calls
- OpenTelemetry.Extensions.Hosting
- AddAspNetCoreInstrumentation on both builders
- UseOtlpExporter once, all signals
- gRPC on localhost:4317 by default
basics
~10 sCall 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 sI 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 linesusing 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
Know that AddOpenTelemetry lives in OpenTelemetry.Extensions.Hosting and that tracing and metrics are configured separately with WithTracing and WithMetrics.
Walk through the full Program.cs: resource name, both instrumentation calls, AddSource and AddMeter for custom code, WithLogging, and why UseOtlpExporter is called once.
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.
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.