skip to content

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%

answer

  1. one runtime type per signal
  2. System.Diagnostics, not an OTel API package
  3. ActivitySource plays the tracer role
  4. Meter creates Counter<T> and Histogram<T>
  5. SDK = listen, process, export

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.

solid answer

~40 s

OpenTelemetry .NET reuses the runtime's own diagnostics types instead of asking you to code against a separate tracing API. A span is a `System.Diagnostics.Activity`, started from an `ActivitySource` whose name plays the tracer's role. Metrics come from a `System.Diagnostics.Metrics.Meter` that creates instruments such as `Counter<T>`, `Histogram<T>` and `UpDownCounter<T>`. Logs are ordinary `ILogger` calls. ASP.NET Core already uses these types: it starts an `Activity` per request and records request metrics on built-in meters. The OpenTelemetry packages add the SDK: `AddOpenTelemetry()` builds tracer, meter and logger providers that subscribe to the source and meter names you list with `AddSource` and `AddMeter`, sample and batch the data, attach a resource such as the service name, and pass it to exporters like OTLP or the console. While nothing listens, instrumented code records almost nothing.

code

csharp · 18 lines
csharp
using System.Diagnostics;
using System.Diagnostics.Metrics;

// registered with AddSingleton<SeatReservation>()
public sealed class SeatReservation(ILogger<SeatReservation> logger, IMeterFactory meterFactory)
{
    private static readonly ActivitySource Source = new("Airline.Booking");
    private readonly Counter<long> _reserved =
        meterFactory.Create("Airline.Booking").CreateCounter<long>("airline.seats.reserved");

    public void Reserve(string flight, string seat)
    {
        using var activity = Source.StartActivity("ReserveSeat"); // trace: an Activity
        activity?.SetTag("airline.flight", flight);
        _reserved.Add(1);                                          // metric: a Meter instrument
        logger.LogInformation("Reserved {Seat} on {Flight}", seat, flight); // log: ILogger
    }
}

go deeper

for a junior

Recall the mapping: Activity and ActivitySource for traces, Meter with Counter<T> or Histogram<T> for metrics, ILogger for logs. Then say the SDK listens to them and exports.

for a middle

Explain why instrumented code is nearly free until a listener subscribes, and how AddSource and AddMeter names connect your types to the SDK providers.

for a senior

Argue for libraries depending only on runtime types and for keeping sampler, resource and exporter choices in the host, so telemetry changes never touch shared code.

for a principal

Weigh standardising source and meter naming across teams against letting each service invent names, given that the SDK only exports what the host explicitly subscribes to.

## Three signals, three runtime types OpenTelemetry defines three signals: **traces** (timed spans that nest into a request tree), **metrics** (numeric measurements aggregated over time) and **logs** (timestamped records). Most languages ship an OpenTelemetry *API* package for instrumentation. .NET took a different route: the runtime already had diagnostics types, so OpenTelemetry .NET maps the specification onto them. | OpenTelemetry concept | .NET type | Namespace | |---|---|---| | Span | `Activity` | `System.Diagnostics` | | Tracer | `ActivitySource` (its name identifies the instrumentation) | `System.Diagnostics` | | Span kind | `ActivityKind` (`Internal`, `Server`, `Client`, `Producer`, `Consumer`) | `System.Diagnostics` | | Span context | `ActivityContext` | `System.Diagnostics` | | Span status | `ActivityStatusCode` via `Activity.SetStatus` | `System.Diagnostics` | | Meter and instruments | `Meter`, `Counter<T>`, `Histogram<T>`, `UpDownCounter<T>` | `System.Diagnostics.Metrics` | | Log record | an `ILogger` call | `Microsoft.Extensions.Logging` | Span attributes are an activity's **tags** (`SetTag`, `AddTag`), and span events are `ActivityEvent`s added with `AddEvent`. ## Where the types come from - `Activity`, `ActivitySource` and the `Meter` family live in **System.Diagnostics.DiagnosticSource**, which is part of the .NET shared framework, so an ASP.NET Core 10 app needs no package to use them. - `ILogger` comes from **Microsoft.Extensions.Logging**, which every ASP.NET Core app already references. - The **OpenTelemetry.Api** package does contain a `Tracer` and `TelemetrySpan` *shim* for people who prefer OpenTelemetry's words (`StartSpan` instead of `StartActivity`). Its README says the SDK works entirely with `Activity`, that both routes produce the same data, and that the recommended way to instrument is the .NET `Activity` API. So a class library that wants to emit spans or metrics references only the runtime types. It never needs to know which exporter, if any, the host application chose. ## What ASP.NET Core already does with them ASP.NET Core is itself instrumented with these types: - the hosting layer starts an `Activity` named `Microsoft.AspNetCore.Hosting.HttpRequestIn` for each request, from an `ActivitySource` named `Microsoft.AspNetCore`; - since .NET 8 it records metrics on built-in meters such as `Microsoft.AspNetCore.Hosting` (`http.server.request.duration`, `http.server.active_requests`); - the framework and your own code log through `ILogger`. None of that leaves the process on its own. An `ActivitySource` hands out activities only when an `ActivityListener` is interested in its name, and an instrument records only when a listener has enabled it. ## What the OpenTelemetry SDK adds The SDK is the listener and the pipeline behind it. In an ASP.NET Core app it is wired with `builder.Services.AddOpenTelemetry()` from the **OpenTelemetry.Extensions.Hosting** package: 1. **Subscription.** `WithTracing` builds a tracer provider that listens to the source names passed to `AddSource`; `WithMetrics` builds a meter provider that listens to the names passed to `AddMeter`; `WithLogging` adds an OpenTelemetry provider behind `ILogger`. 2. **Decisions and enrichment.** A sampler decides which traces are recorded, and a resource (for example the service name from `ConfigureResource(r => r.AddService("booking-api"))`) is stamped on everything. 3. **Processing and aggregation.** Finished spans and log records are batched; measurements are aggregated into sums and histograms per collection interval. 4. **Export.** Exporters send the result out, for example over OTLP with `UseOtlpExporter()` from **OpenTelemetry.Exporter.OpenTelemetryProtocol**, or to the console for local debugging. The SDK is also responsible for shutting the providers down cleanly with the host, which flushes what is still buffered. ## Why the split matters in practice - Code instrumented with `ActivitySource` and `Meter` costs little when nobody listens, so libraries can instrument freely. - Turning telemetry on or off, changing the exporter or the sampler is a host decision in `Program.cs`, not a code change in every class. - The same activities feed other consumers too: for example, ASP.NET Core's ProblemDetails writer reads `Activity.Current?.Id` for its `traceId` field even when no SDK is installed. ## A worked example: one class, three signals Take a `SeatReservation` service in the booking API that reserves a seat on a flight: 1. It holds a `static readonly ActivitySource` named `Airline.Booking`. Each call to `Reserve` starts an activity called `ReserveSeat`; because a request is in progress, the new activity becomes a child of the request's activity and the trace shows the reservation nested inside `POST /checkout`. 2. It asks the injected `IMeterFactory` for a meter named `Airline.Booking` and creates a `Counter<long>` called `airline.seats.reserved`. Each reservation adds one. 3. It logs through `ILogger<SeatReservation>` with a message template, so the seat and flight stay as named properties. Nothing in that class mentions OpenTelemetry. Whether the span, the counter and the log line ever leave the process is decided in `Program.cs`: the source name must appear in `AddSource`, the meter name in `AddMeter`, and `WithLogging` must be present. Remove the SDK and the class still compiles and runs; the instrumentation simply records nothing for an exporter. ## Common confusions - An `Activity` is a full span with start time, duration, tags, status and parent, not only a correlation id. - `DiagnosticListener` is the older publish/subscribe event API in the same assembly; ASP.NET Core still raises events on it, but it is not how you create spans. - Logs need no new API: keep calling `ILogger`, and let `WithLogging` export them.

  • Should a shared class library reference the OpenTelemetry package to emit spans?
    No. It should create an `ActivitySource` and a `Meter` from the runtime's `System.Diagnostics` types and document their names. The host application decides whether to install the SDK, which names to subscribe to with `AddSource` and `AddMeter`, and where to export. Referencing the SDK from a library would drag exporter and pipeline choices into every consumer.
  • What does the OpenTelemetry.Api shim give you, and do you need it?
    It offers `Tracer` and `TelemetrySpan` wrappers so code can use OpenTelemetry's vocabulary such as `StartSpan`. Underneath it still creates `Activity` objects, and the SDK sees the same data either way. The OpenTelemetry .NET README recommends the plain `Activity` API, so most ASP.NET Core code never references the shim.

  • Creating a span in .NET requires a reference to the OpenTelemetry.Api package.
  • An Activity is just a correlation id with no timing or tags.
  • Meter and Counter<T> are types from the OpenTelemetry SDK, not the runtime.
  • ASP.NET Core needs an OpenTelemetry package before it can produce request metrics.
  • OpenTelemetry cannot collect ILogger output; logs need a separate OpenTelemetry API.