Frameworks 11 min read

OpenTelemetry for ASP.NET Core and .NET

Tracing, metrics and logs for a .NET web app, from a Program.cs that works to the reasons traces go missing. Tested with ASP.NET Core 10 and OpenTelemetry .NET 1.21 (November 2026).

David Granzin By David Granzin

Minimal setup

Three steps give you traces, metrics and logs over OTLP. Add the packages:

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

Register OpenTelemetry in Program.cs, before builder.Build():

Program.cs

using OpenTelemetry;
using OpenTelemetry.Metrics;
using OpenTelemetry.Trace;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddOpenTelemetry()
    .WithTracing(tracing => tracing
        .AddAspNetCoreInstrumentation()
        .AddHttpClientInstrumentation())
    .WithMetrics(metrics => metrics
        .AddAspNetCoreInstrumentation()
        .AddHttpClientInstrumentation()
        .AddRuntimeInstrumentation())
    .WithLogging()
    .UseOtlpExporter();

var app = builder.Build();

app.MapGet("/orders/{id}", (string id) => Results.Ok(new { id }));

app.Run();

Point the exporter at a Collector or backend and run:

export OTEL_SERVICE_NAME="checkout"
export OTEL_EXPORTER_OTLP_ENDPOINT="http://localhost:4318"
export OTEL_EXPORTER_OTLP_PROTOCOL="http/protobuf"

dotnet run
One exporter call serves every signal you enabled. Batch sizes are the SDK defaults.

Leave the variables out and two defaults apply: the exporter sends gRPC to http://localhost:4317, and the service is named unknown_service:dotnet.

What a request produces

The console exporter shows each span before a backend exists. It works next to UseOtlpExporter():

// dotnet add package OpenTelemetry.Exporter.Console
.WithTracing(tracing => tracing
    .AddAspNetCoreInstrumentation()
    .AddHttpClientInstrumentation()
    .AddConsoleExporter())

A request to /orders/42 prints this (start time trimmed):

Activity.TraceId:            103cb8251fdcb8b574852f87c1c76a14
Activity.SpanId:             28d78436842b367d
Activity.TraceFlags:         Recorded, RandomTraceId
Activity.DisplayName:        GET /orders/{id}
Activity.Kind:               Server
Activity.Duration:           00:00:00.0087850
Activity.Tags:
    http.request.method: GET
    server.address: 127.0.0.1
    server.port: 5199
    url.scheme: http
    url.path: /orders/42
    network.protocol.version: 1.1
    http.route: /orders/{id}
    http.response.status_code: 200
Instrumentation scope (ActivitySource):
    Name: Microsoft.AspNetCore
Resource associated with Activity:
    telemetry.sdk.name: opentelemetry
    telemetry.sdk.language: dotnet
    telemetry.sdk.version: 1.21.0
    service.name: unknown_service:dotnet
  • A span is an Activity. System.Diagnostics.Activity is the .NET span type.
  • The name is the route template. GET /orders/{id}, not the URL, so every order shares one span name and one http.route.
  • A 4xx is not an error. A 404 leaves the status unset. An unhandled exception gives a 500, status Error and error.type set to the exception type.
  • Query strings are redacted. ?token=abc is recorded as ?token=Redacted.

.NET 8 and 9 support

Which package line to install depends on your target framework. As of November 2026, the 1.21 packages ship builds for .NET 10, .NET 11 and netstandard2.0. The net8.0 and net9.0 builds that 1.20 had are gone.

On .NET 8, testedPackages 1.21Packages 1.20
Build15 warningsClean
Spans exportedYesYes
Request span nameGETGET /orders/{id}

The 1.21 warnings come from the 11.0 runtime libraries the packages depend on:

warning : System.Diagnostics.DiagnosticSource 11.0.0 doesn't support net8.0 and
has not been tested with it. Consider upgrading your TargetFramework to net10.0
or later.

On .NET 8 or 9, pin the 1.20 line (OpenTelemetry.Extensions.Hosting 1.20.1, OpenTelemetry.Instrumentation.AspNetCore 1.20.2). The snippets in this guide compile against both lines.

Instrumentation packages

Each library has its own NuGet package and an Add...Instrumentation() call. Check the release status first: dotnet add package refuses a prerelease-only package unless you pass --prerelease.

LibraryPackageRelease status
ASP.NET CoreOpenTelemetry.Instrumentation.AspNetCoreStable
HttpClientOpenTelemetry.Instrumentation.HttpStable
SqlClientOpenTelemetry.Instrumentation.SqlClientStable
Runtime metricsOpenTelemetry.Instrumentation.RuntimeStable
Entity Framework CoreOpenTelemetry.Instrumentation.EntityFrameworkCorePrerelease (beta)
gRPC clientOpenTelemetry.Instrumentation.GrpcNetClientPrerelease (beta)
StackExchange.RedisOpenTelemetry.Instrumentation.StackExchangeRedisPrerelease (beta)
Process metricsOpenTelemetry.Instrumentation.ProcessPrerelease (rc)
PostgreSQL (Npgsql)Npgsql.OpenTelemetryStable, versioned with Npgsql

Since .NET 9, HttpClient writes its own span attributes, and AddHttpClientInstrumentation() subscribes to them. Client spans are named after the method alone (GET) with the target in url.full.

ASP.NET Core reads the W3C traceparent header and HttpClient writes it, so two instrumented .NET services join one trace with no code. The context propagation guide covers where that breaks.

EF Core and SqlClient

Database spans come from one of two packages, depending on how you query:

// EF Core (any relational provider). The package is prerelease:
// dotnet add package OpenTelemetry.Instrumentation.EntityFrameworkCore --prerelease
.WithTracing(tracing => tracing
    .AddAspNetCoreInstrumentation()
    .AddEntityFrameworkCoreInstrumentation())

// Raw ADO.NET or Dapper on SQL Server:
// dotnet add package OpenTelemetry.Instrumentation.SqlClient
.WithTracing(tracing => tracing
    .AddAspNetCoreInstrumentation()
    .AddSqlClientInstrumentation())

The EF Core package traces relational providers, not Cosmos DB. By default the beta writes the older attribute names and uses the database name as the span name. OTEL_SEMCONV_STABILITY_OPT_IN=database switches it to the current conventions. Both, from a SQLite test:

# default
Activity.DisplayName:        main
    db.system: sqlite
    db.name: main
    db.statement: SELECT COUNT(*) FROM "Orders" AS "o"

# OTEL_SEMCONV_STABILITY_OPT_IN=database
Activity.DisplayName:        SELECT
    db.system.name: sqlite
    db.namespace: main
    db.query.text: SELECT COUNT(*) FROM "Orders" AS "o"
    db.query.summary: SELECT
  • SqlClient covers Microsoft.Data.SqlClient and System.Data.SqlClient, and documents the current names (db.system.name, db.namespace, db.query.text) with no opt-in. Not run for this guide, since it needs a SQL Server.
  • Parameter values are not recorded unless you opt in through OTEL_DOTNET_EXPERIMENTAL_SQLCLIENT_ENABLE_TRACE_DB_QUERY_PARAMETERS or the EF Core equivalent. Leave that off in production: parameters hold emails, tokens and card numbers.
  • Both packages on SQL Server can give two spans for one query, one per layer. Pick one, or use the Filter option both have.
  • PostgreSQL has its own package from the driver: add Npgsql.OpenTelemetry and call .AddNpgsql() on the tracing builder.

Custom spans with ActivitySource

Your own spans use types .NET already has: an ActivitySource is the tracer, an Activity is the span, tags are attributes. Create one static source per component and start activities from it:

OrderService.cs

using System.Diagnostics;

public static class Telemetry
{
    public const string SourceName = "Checkout.Orders";
    public static readonly ActivitySource Source = new(SourceName);
}

public class OrderService(PaymentClient payments)
{
    public async Task<Receipt> PlaceOrderAsync(Order order)
    {
        // Null when nothing listens to the source or the trace is not sampled.
        using var activity = Telemetry.Source.StartActivity("PlaceOrder");
        activity?.SetTag("order.id", order.Id);
        activity?.SetTag("order.item_count", order.Items.Count);

        try
        {
            return await payments.ChargeAsync(order);
        }
        catch (Exception ex)
        {
            activity?.SetStatus(ActivityStatusCode.Error, ex.Message);
            activity?.AddException(ex);
            throw;
        }
    }
}

Then register the source. This is the step people miss:

.WithTracing(tracing => tracing
    .AddSource(Telemetry.SourceName)   // or a wildcard: "Checkout.*"
    .AddAspNetCoreInstrumentation()
    .AddHttpClientInstrumentation())

Without AddSource, StartActivity returns null and nothing fails. With it, the span joins the request's trace. One request from the test app, whose handler also runs an EF Core query and an HttpClient call:

Span names, scopes and durations as the console exporter printed them. PlaceOrder is the only span written by hand.
  • Nesting is automatic. The new activity becomes Activity.Current, so calls made inside it are recorded as its children.
  • Errors are explicit. SetStatus(ActivityStatusCode.Error) marks the span as failed and AddException attaches an exception event with type, message and stack trace. Do this for exceptions only, never for a handled 404 or validation failure.

To add a tag to the request span that already exists, skip the new span and use the current activity:

app.MapGet("/orders/{id}", (string id) =>
{
    // Adds a tag to the request span ASP.NET Core already started.
    Activity.Current?.SetTag("order.id", id);
    return Results.Ok(new { id });
});

Built-in metrics in .NET 8 and later

Request and connection metrics need no code of yours. Since .NET 8, ASP.NET Core and HttpClient publish them under OpenTelemetry semantic convention names. AddAspNetCoreInstrumentation() and AddHttpClientInstrumentation() on the metrics builder subscribe to these meters:

MeterWhat it reports
Microsoft.AspNetCore.Hostinghttp.server.request.duration, http.server.active_requests
Microsoft.AspNetCore.Server.Kestrelkestrel.active_connections, kestrel.connection.duration, kestrel.queued_connections
Microsoft.AspNetCore.RoutingRoute match attempts
Microsoft.AspNetCore.DiagnosticsExceptions seen by the exception handler
Microsoft.AspNetCore.RateLimitingLeases, queue length and wait time
System.Net.Httphttp.client.request.duration, http.client.open_connections, http.client.request.time_in_queue
System.Net.NameResolutionDNS lookup duration

To take only some of them, skip the instrumentation call and name the meters. The same call registers a Meter of your own:

.WithMetrics(metrics => metrics
    .AddMeter("Microsoft.AspNetCore.Hosting")
    .AddMeter("Microsoft.AspNetCore.Server.Kestrel")
    .AddMeter("System.Net.Http")
    .AddMeter("Checkout.Orders"))   // your own Meter

Build latency and error rate charts from http.server.request.duration. It is a histogram in seconds, tagged with http.route, http.request.method and http.response.status_code. The route tag is the template, so cardinality is bounded by your endpoint count.

Logs with TraceId and SpanId

Logs written inside a request carry that request's trace and span IDs with no extra code. WithLogging() adds an OpenTelemetry provider to the normal pipeline, and your code keeps using ILogger:

builder.Services.AddOpenTelemetry()
    .WithLogging(
        logging => { },
        options =>
        {
            options.IncludeFormattedMessage = true;
            options.IncludeScopes = true;
        })
    .UseOtlpExporter();

app.MapGet("/orders/{id}", (string id, ILogger<Program> logger) =>
{
    // Exported with the TraceId and SpanId of the request span.
    logger.LogInformation("Loading order {OrderId}", id);
    return Results.Ok(new { id });
});

The exported record, printed by the console log exporter:

LogRecord.TraceId:                 1f99af4e82f9a0cedf641f5dfb3907de
LogRecord.SpanId:                  cfc841452fa77bac
LogRecord.CategoryName:            Program
LogRecord.Severity:                Info
LogRecord.FormattedMessage:        Loading order 42
LogRecord.Body:                    Loading order {OrderId}
LogRecord.Attributes (Key:Value):
    OrderId: 42
  • IncludeFormattedMessage exports the rendered text next to the template. Off by default.
  • IncludeScopes exports values from logger.BeginScope. Off by default.
  • Placeholders become attributes. OrderId is exported either way, which is the reason to use message templates rather than string interpolation.
  • Levels still come from appsettings.json. A record filtered out there never reaches the exporter. Other providers, such as the console, keep working.

For the IDs in console output too, turn on scopes. The host already adds TraceId, SpanId and ParentId to every log scope, and the default formatter hides them:

// Console logs as JSON, with TraceId and SpanId in the Scopes array.
builder.Logging.AddJsonConsole(options => options.IncludeScopes = true);
{"EventId":0,"LogLevel":"Information","Category":"Program",
 "Message":"Loading order 42",
 "State":{"OrderId":"42","{OriginalFormat}":"Loading order {OrderId}"},
 "Scopes":[{"Message":"SpanId:d92cc05c05060221, TraceId:3b5f1fbd8cf9e6a0213e9e5507d16cec, ParentId:0000000000000000",
            "SpanId":"d92cc05c05060221",
            "TraceId":"3b5f1fbd8cf9e6a0213e9e5507d16cec",
            "ParentId":"0000000000000000"}, ...]}

Using Serilog? You can keep it. Either pass writeToProviders: true to AddSerilog or UseSerilog, so Serilog events also reach the OpenTelemetry provider that WithLogging() registered. Or add Serilog.Sinks.OpenTelemetry and call WriteTo.OpenTelemetry(), which sends OTLP itself and copies TraceId and SpanId from Activity.Current. The sink also defaults to gRPC on http://localhost:4317. Both are taken from the packages' docs (sink 4.3.0, Serilog.AspNetCore 11.0.0) and were not run here.

Filter health checks

Probes that hit /healthz every few seconds fill the trace list and tell you nothing. The Filter option drops them:

Program.cs

builder.Services.AddHealthChecks();

builder.Services.AddOpenTelemetry()
    .WithTracing(tracing => tracing
        .AddAspNetCoreInstrumentation(options =>
        {
            // false = no span for this request, or for anything it calls.
            options.Filter = context =>
                !context.Request.Path.StartsWithSegments("/healthz");
        })
        .AddHttpClientInstrumentation(options =>
        {
            options.FilterHttpRequestMessage = request =>
                request.RequestUri?.Host != "169.254.169.254";
        }));

var app = builder.Build();
app.MapHealthChecks("/healthz");
  • Children go too. When Filter returns false, the request span and, with the default sampler, its children are not recorded. A health check that queries the database leaves no orphan span.
  • Keep it cheap. The filter runs for every request.
  • Outgoing calls have FilterHttpRequestMessage, for polling clients and metadata endpoints.
  • Metrics are unaffected. Health checks still count in http.server.request.duration, under their own route.

On the same options, RecordException = true stores unhandled exceptions on the request span and EnrichWithHttpRequest adds tags from the request.

Production configuration

Production adds a service identity, a sampler, batch limits, a clean shutdown and a destination. Start with identity: service.name, service.version and deployment.environment.name are how a backend groups telemetry, compares releases and separates staging from production.

using OpenTelemetry.Resources;

builder.Services.AddOpenTelemetry()
    .ConfigureResource(resource => resource
        .AddService(
            serviceName: "checkout",
            serviceNamespace: "shop",
            serviceVersion: "1.4.2")
        .AddAttributes(new Dictionary<string, object>
        {
            ["deployment.environment.name"] =
                builder.Environment.EnvironmentName.ToLowerInvariant(),
        }))

The same attributes can come from three places. When they disagree, the higher row wins:

SourceTested result
ConfigureResource in codeWith OTEL_SERVICE_NAME=fromenv also set, the resource said service.name: checkout
OTEL_SERVICE_NAME, OTEL_RESOURCE_ATTRIBUTESUsed when code does not set the key. Extra keys are merged in.
builder.AddOpenTelemetry() on the host builderSeeds service.name: app and deployment.environment.name: production from the host
Nothingservice.name: unknown_service:dotnet

The third row means calling AddOpenTelemetry() on builder instead of builder.Services. AddService also generates a random service.instance.id per process.

The SDK and UseOtlpExporter() read the rest from the environment:

.env

# Identity
OTEL_SERVICE_NAME=checkout
OTEL_RESOURCE_ATTRIBUTES=service.version=1.4.2,deployment.environment.name=production

# Export
OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4318
OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf
OTEL_EXPORTER_OTLP_COMPRESSION=gzip

# Keep 10% of new traces, follow the caller's decision otherwise
OTEL_TRACES_SAMPLER=parentbased_traceidratio
OTEL_TRACES_SAMPLER_ARG=0.1

# Span batching (these are the defaults) and metric interval
OTEL_BSP_SCHEDULE_DELAY=5000
OTEL_BSP_MAX_QUEUE_SIZE=2048
OTEL_BSP_MAX_EXPORT_BATCH_SIZE=512
OTEL_METRIC_EXPORT_INTERVAL=60000
  • Sampling. The default records every new trace and follows the caller's decision when there is one. The two sampler variables keep about one new trace in ten. That decision is made at the first span, before the request can fail. To keep every error and slow trace, sample in a Collector (see the sampling guide).
  • Batching. Spans and logs leave from a background thread every 5 seconds or 512 items, from a queue of 2048. A full queue drops new spans rather than blocking a request, so raise the queue size first for a bursty service. Metrics are exported every 60 seconds.
  • Shutdown. The host owns the providers and flushes them when it stops. In a test, an app sent SIGTERM one second after a request still delivered its traces, logs and metrics. A killed process loses its queue. A console app using Sdk.CreateTracerProviderBuilder() must dispose the provider itself.
  • Destination. An OpenTelemetry Collector next to the app keeps keys, retries and tail sampling out of your process. Sending straight to a backend is one less thing to run.

Common problems

Most failures here are silent, because the SDK never throws into your request path. An app exporting to the wrong port logs nothing by default. Turn on self-diagnostics first:

export OTEL_DOTNET_SELF_DIAGNOSTICS_SINKS=stdout,stderr
export OTEL_LOG_LEVEL=warn

OTEL_LOG_LEVEL alone prints nothing, because no sink is enabled. At warn you also get a harmless line per unsubscribed framework meter.

SymptomUsual causeFix
Request spans appear, your own spans do notThe ActivitySource name is not registered.AddSource("Your.Source")
NullReferenceException on activity.SetTagStartActivity returned nullUse activity?. everywhere
Nothing arrives, no error in the appgRPC exporter pointed at an HTTP port, or the reverseMatch OTEL_EXPORTER_OTLP_PROTOCOL to the port
Traces arrive, logs or metrics do notThat signal was never enabledAdd WithLogging() or WithMetrics(...)
Service is named unknown_service:dotnetNo service name setOTEL_SERVICE_NAME or AddService
Spans are named GET with no route1.21 packages on .NET 8 or 9Pin the 1.20 packages
Only some requests have tracesA ratio sampler, here or in the calling serviceCheck OTEL_TRACES_SAMPLER on both sides

No traces at all

Work from the app outward:

  • Is tracing enabled? UseOtlpExporter() exports only the signals you turned on. No WithTracing(...), nothing to export.
  • Is anything producing spans? WithTracing() with no instrumentation and no AddSource listens to nothing.
  • Does the console exporter print them? Then the SDK is fine and the problem is the endpoint, the protocol or a header.
  • Did the environment variables reach the process? A variable exported in your shell is not set in a container, a systemd unit or an IIS app pool.
  • Is a parent telling you not to sample? A request whose traceparent sampled flag is 00 is not recorded under the default sampler. A caller sampling at 0% turns your traces off too.

With nothing listening on the default port, self-diagnostics shows each failed export:

[Warning] OpenTelemetry-Exporter-OpenTelemetryProtocol: Transient HTTP error occurred
when communicating with
http://localhost:4317/opentelemetry.proto.collector.trace.v1.TraceService/Export.
Exception: System.Net.Http.HttpRequestException: Connection refused (localhost:4317)

Activity is null

ActivitySource.StartActivity returns null for two reasons, and only the first is a bug:

Both null paths were reproduced: by removing AddSource, and by sending a traceparent ending in -00 with the source registered.
  • Never remove the ?. operators. A sampled-out request returns null in a correct setup.
  • Keep the source name in one constant and use it in both new ActivitySource(...) and AddSource. For a library you do not control, AddSource("Vendor.*") catches all of its sources.
  • Activity.Current flows with the async context. It is still set inside a Task.Run started from a request, and null in a hosted service or timer callback. Start your own activity there.

gRPC vs http/protobuf

The .NET exporter defaults to gRPC, while most hosted endpoints and copied examples use HTTP on 4318. Set only the endpoint and the exporter speaks gRPC to an HTTP port, failing every export in the background. With self-diagnostics on:

[Error] OpenTelemetry-Exporter-OpenTelemetryProtocol: HTTP request to
http://127.0.0.1:4318/opentelemetry.proto.collector.trace.v1.TraceService/Export failed.
Exception: System.Net.Http.HttpRequestException: The HTTP/2 server sent invalid data
on the connection. HTTP/2 error code 'PROTOCOL_ERROR' (0x1). (HttpProtocolError)

The gRPC service name in the URL is the giveaway. Set the protocol too, with OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf or in code:

using OpenTelemetry.Exporter;

// Base URL: /v1/traces, /v1/metrics and /v1/logs are appended.
.UseOtlpExporter(OtlpExportProtocol.HttpProtobuf, new Uri("http://localhost:4318"));

// Per-signal exporter: the path is yours to write.
.AddOtlpExporter(options =>
{
    options.Protocol = OtlpExportProtocol.HttpProtobuf;
    options.Endpoint = new Uri("http://localhost:4318/v1/traces");
})
Where the URL is setHow it is used
OTEL_EXPORTER_OTLP_ENDPOINTBase URL. /v1/traces, /v1/metrics, /v1/logs are appended.
UseOtlpExporter(protocol, uri)Base URL, same as above.
Endpoint in AddOtlpExporter optionsUsed as written. Given http://localhost:4318, the exporter posted traces to /.

The OTLP guide explains each export status code.

NotSupportedException at startup

UseOtlpExporter() cannot be mixed with per-signal AddOtlpExporter() calls, and can only be called once. The host fails to start with:

System.NotSupportedException: Signal-specific AddOtlpExporter methods and the
cross-cutting UseOtlpExporter method being invoked on the same IServiceCollection
is not supported.

It usually follows pasting a snippet that ends in .AddOtlpExporter() into an app that already uses UseOtlpExporter(). Use the per-signal calls only when signals go to different endpoints.

Aspire dashboard and zero-code instrumentation

Two optional tools: a local viewer, and instrumentation that needs no code. Neither was run for this guide, so the commands come from each project's docs.

The .NET Aspire dashboard shows traces, metrics and structured logs from one container, without the rest of Aspire:

docker run --rm -d --name aspire-dashboard \
  -p 18888:18888 -p 4317:18889 -p 4318:18890 \
  mcr.microsoft.com/aspire/dashboard:latest

The UI is at http://localhost:18888, with OTLP on host ports 4317 (gRPC) and 4318 (HTTP). Data is held in memory, so keep it to development.

The OpenTelemetry .NET automatic instrumentation attaches through a CLR profiler and a startup hook. It instruments ASP.NET Core, HttpClient, SqlClient, EF Core and other libraries with no package references:

# After running otel-dotnet-auto-install.sh from the project's releases page
. $HOME/.otel-dotnet-auto/instrument.sh

OTEL_SERVICE_NAME=checkout \
OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318 \
OTEL_DOTNET_AUTO_TRACES_ADDITIONAL_SOURCES=Checkout.Orders \
dotnet run
  • Its exporter default is http/protobuf on port 4318, not gRPC.
  • Your own sources still need registering, through OTEL_DOTNET_AUTO_TRACES_ADDITIONAL_SOURCES.
  • Configuration is environment variables only, so there is no place for a Filter callback.
  • Do not run it on an app that already calls AddOpenTelemetry(). You can get duplicate spans or conflicting package versions.

Use it for services you cannot rebuild. For one you own, the code setup gives more control.

Send it to Maple

Maple accepts OTLP directly, so the setup above needs no code change. Set the endpoint and pass your ingest key as a bearer token. Keep the protocol line: without it the .NET exporter uses gRPC.

export OTEL_SERVICE_NAME="checkout"
export OTEL_EXPORTER_OTLP_ENDPOINT="https://ingest.maple.dev"
export OTEL_EXPORTER_OTLP_HEADERS="Authorization=Bearer YOUR_INGEST_KEY"
export OTEL_EXPORTER_OTLP_PROTOCOL="http/protobuf"
A trace in Maple shown as a timeline waterfall: a POST /api/checkout request crossing 6 services in 15 spans, with the failing span marked as an error.
The span tree from this guide, as a backend draws it: one row per span, nested by parent, errors marked.

The Maple .NET instrumentation docs cover setting the same values in code.

Sources and further reading

FAQ

よくある質問

How do I add OpenTelemetry to an ASP.NET Core app?
Install OpenTelemetry.Extensions.Hosting, OpenTelemetry.Exporter.OpenTelemetryProtocol and the AspNetCore and Http instrumentation packages. In Program.cs call builder.Services.AddOpenTelemetry(), enable WithTracing, WithMetrics and WithLogging, and finish with UseOtlpExporter(). The exporter reads its endpoint from OTEL_EXPORTER_OTLP_ENDPOINT.
Why is my Activity null in .NET?
ActivitySource.StartActivity returns null when nothing listens to that source, or when the sampler dropped the trace. Register the source name with AddSource on the tracer provider, check that the name matches exactly, and keep the null-conditional operator (activity?.SetTag) because a sampled-out request still returns null.
What is the difference between Activity and a span in .NET?
They are the same thing. .NET had System.Diagnostics.Activity before OpenTelemetry existed, so the OpenTelemetry .NET SDK uses Activity as its span type and ActivitySource as its tracer. Tags are attributes and ActivityEvent is a span event.
Does the .NET OTLP exporter use gRPC or HTTP by default?
gRPC, sending to http://localhost:4317. To use OTLP over HTTP, set OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf and point the endpoint at port 4318. The zero-code automatic instrumentation is different: it defaults to http/protobuf.
Which .NET versions does OpenTelemetry support?
As of November 2026, the OpenTelemetry .NET 1.21 packages ship builds for .NET 10, .NET 11 and netstandard2.0, and the core SDK also targets .NET Framework 4.6.2. A .NET 8 or 9 app restores the netstandard2.0 build, compiles with warnings and loses route-based span names. On .NET 8 or 9, pin the 1.20 packages, which still include net8.0 builds.
Is OpenTelemetry built into .NET?
The instrumentation APIs are. ActivitySource and Activity for spans and Meter for metrics live in System.Diagnostics, and ASP.NET Core and HttpClient already emit through them. Collecting and exporting that data is not built in: the OpenTelemetry SDK and the OTLP exporter are NuGet packages you add and register with AddOpenTelemetry().
How do I exclude health checks from ASP.NET Core traces?
Set the Filter option of AddAspNetCoreInstrumentation to a function that returns false for the health check path, for example context => !context.Request.Path.StartsWithSegments("/healthz"). The request span and its child spans are then not recorded.

今日、最初のトレースを。

SDKを追加し、OTLPエクスポーターをMapleに向ければトレースが届きます。

maple.dev:OpenTelemetryの上のオブザーバビリティ