OpenTelemetry
C# / .NET
Quick Start

C# / .NET (OpenTelemetry)

Let a coding agent do this setup
1Install the Traceway skills
2Run it in Claude Code

It adds OpenTelemetry to your .NET service and checks that data arrives. How the setup skill works

Instrument an ASP.NET Core service with the OpenTelemetry .NET SDK and export traces, logs and metrics to Traceway over OTLP/HTTP.

.NET has OpenTelemetry built into the runtime: spans are System.Diagnostics.Activity, metrics are System.Diagnostics.Metrics, and logs are ILogger. The setup is a few lines in Program.cs that tell the SDK what to collect and where to send it. All three signals are stable.

Requirements

  • .NET 8 or newer. This guide was checked with .NET 10.
  • A Traceway project created with framework OpenTelemetry, and that project's token.

Install

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

This guide was checked with version 1.21.0 of all three.

Configure

The exporters and the resource read these from the process environment. Nothing about the destination is set in code.

export OTEL_SERVICE_NAME=my-dotnet-service
export OTEL_RESOURCE_ATTRIBUTES="service.version=1.0.0"
export OTEL_EXPORTER_OTLP_ENDPOINT=https://cloud.tracewayapp.com/api/otel
export OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf
export OTEL_EXPORTER_OTLP_HEADERS="Authorization=Bearer your-project-token"
export OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE=delta

OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf is not optional. The .NET exporter defaults to gRPC, and Traceway has no gRPC listener. Without the line the service starts, serves traffic and prints nothing while every export is lost. A wrong token and a wrong path are just as silent. To see exporter errors, set OTEL_DOTNET_SELF_DIAGNOSTICS_SINKS=stderr.

  • OTEL_EXPORTER_OTLP_ENDPOINT takes the base URL. Read from the environment, the exporter appends /v1/traces, /v1/metrics and /v1/logs. If you set options.Endpoint in code instead, nothing is appended, and you have to write the full path for each signal yourself.
  • OTEL_SERVICE_NAME becomes the Server Name on every endpoint, task and issue. Without it the name is unknown_service:dotnet. Version travels in OTEL_RESOURCE_ATTRIBUTES. There is no OTEL_SERVICE_VERSION variable.
  • The temporality line makes counters and histograms send what changed since the last export, not the running total.

Instrument the Server

Program.cs
using System.Diagnostics;
using System.Diagnostics.Metrics;
using OpenTelemetry.Logs;
using OpenTelemetry.Metrics;
using OpenTelemetry.Trace;
 
var builder = WebApplication.CreateBuilder(args);
 
builder.Services.AddOpenTelemetry()
    .WithTracing(tracing => tracing
        .AddAspNetCoreInstrumentation(options => options.RecordException = true)
        .AddSource(Telemetry.Name)
        .AddOtlpExporter())
    .WithMetrics(metrics => metrics
        .AddMeter(Telemetry.Name)
        .AddOtlpExporter());
 
builder.Logging.AddOpenTelemetry(logging =>
{
    logging.IncludeFormattedMessage = true;
    logging.AddOtlpExporter();
});
 
var app = builder.Build();
 
app.MapGet("/users/{id}", (string id, ILogger<Program> logger) =>
{
    logger.LogInformation("looking up user {UserId}", id);
 
    using var span = Telemetry.Source.StartActivity("load-user");
    span?.SetTag("user.id", id);
 
    return new { id, name = $"user-{id}" };
});
 
app.MapGet("/boom", string () => throw new InvalidOperationException("boom: something went wrong"));
 
app.MapGet("/run-job", () =>
{
    var requestSpan = Activity.Current;
    Activity.Current = null;
    using (Telemetry.Source.StartActivity("cleanup-expired-sessions", ActivityKind.Consumer))
    {
        Telemetry.SessionsCleaned.Add(7, new KeyValuePair<string, object?>("job", "cleanup-expired-sessions"));
    }
    Activity.Current = requestSpan;
 
    return new { cleaned = 7 };
});
 
app.Run();
 
static class Telemetry
{
    public const string Name = "UsersApi";
    public static readonly ActivitySource Source = new(Name);
    public static readonly Meter Meter = new(Name);
    public static readonly Counter<long> SessionsCleaned = Meter.CreateCounter<long>("app.sessions_cleaned");
}

Run it with the variables from Configure set:

ASPNETCORE_URLS=http://localhost:8080 dotnet run

AddSource and AddMeter are an allow list. A span from an ActivitySource, or a metric from a Meter, whose name is not listed is dropped without a message.

What Arrives With No Application Code

TracewayWhere it comes from
Endpoints, grouped by route patternAddAspNetCoreInstrumentation() sets http.route from the matched route: MapGet("/users/{id}") becomes GET /users/{id}
Status codes, including 500 on an unhandled exceptionThe same instrumentation
Logs, linked to the trace that produced thembuilder.Logging.AddOpenTelemetry(...) exports every ILogger line with its trace and span id

Route constraints stay in the name as you wrote them, so MapGet("/items/{id:int}") is listed as GET /items/{id:int}.

Exceptions

An unhandled exception creates no Issue by default. The request span gets status Error and the endpoint row shows 500, but the exception itself is not recorded. Set RecordException = true on the ASP.NET Core instrumentation, as Program.cs does.

One more case needs code. If your application calls app.UseExceptionHandler(), which most production setups do, the handler catches the exception before the instrumentation sees it, and RecordException has nothing to record. Add an exception handler that puts it on the request span and lets the normal handler write the response:

builder.Services.AddExceptionHandler<RecordingHandler>();
 
class RecordingHandler : Microsoft.AspNetCore.Diagnostics.IExceptionHandler
{
    public ValueTask<bool> TryHandleAsync(HttpContext context, Exception exception, CancellationToken cancellationToken)
    {
        Activity.Current?.AddException(exception);
        return ValueTask.FromResult(false);
    }
}

Use Activity.Current?.AddException(exception) the same way for an error you catch yourself.

Logs

builder.Logging.AddOpenTelemetry(...) sends every ILogger line to Traceway. Lines written inside a request carry its trace id with no further setup.

Set IncludeFormattedMessage = true. Without it the log body is the message template, looking up user {UserId}, and the value is only an attribute. With it the body reads looking up user 101 and the template is kept as an attribute.

Background Tasks

A job appears under Tasks when its span has kind Consumer. A root span with the default kind is dropped.

using (Telemetry.Source.StartActivity("cleanup-expired-sessions", ActivityKind.Consumer))
{
    Cleanup();
}

The span name is the task name, so keep it stable and put job ids and batch sizes in tags. StartActivity always parents the new span to Activity.Current, and passing a default parent context does not change that. A job started from inside a request is therefore a child of that request unless you clear Activity.Current around it, as /run-job does in Program.cs. A BackgroundService or a queue consumer has no current activity and needs only the StartActivity call.

Custom Metrics

static readonly Meter Meter = new("UsersApi");
static readonly Counter<long> SessionsCleaned = Meter.CreateCounter<long>("app.sessions_cleaned");
 
SessionsCleaned.Add(7, new KeyValuePair<string, object?>("job", "cleanup-expired-sessions"));

List the meter with .AddMeter("UsersApi"). The counter then appears in metric discovery as app.sessions_cleaned, with job as a tag you can group by. Metrics export every 60 seconds by default. While you are checking the integration, set OTEL_METRIC_EXPORT_INTERVAL=5000, and remove it afterwards.

Program.cs does not call AddAspNetCoreInstrumentation() on the metrics builder, and that is on purpose. That call adds http.server.request.duration, http.server.active_requests and a set of kestrel.* and aspnetcore.* metrics. Traceway already computes request counts and latency from spans, so leave it out unless you need those metrics for something else.

Zero-Code Alternative

The OpenTelemetry project also ships automatic instrumentation for .NET (opens in a new tab), which attaches to an unmodified application through environment variables and reads the same OTEL_* settings. It was not run for this page.

Verify It Worked

Start the service, then send a few requests:

curl localhost:8080/users/101
curl localhost:8080/users/102
curl localhost:8080/users/103
curl localhost:8080/boom
curl localhost:8080/run-job

Set the dashboard time picker to the last 15 minutes and check:

  1. Endpoints. One row GET /users/{id} with a count of 3, and GET /boom with status 500.
  2. Issues. System.InvalidOperationException: boom: something went wrong with its stack trace. A failed endpoint row with no Issue means RecordException is not set.
  3. Logs. Three looking up user lines, each linked to its trace.
  4. Tasks. cleanup-expired-sessions.
  5. Metrics. app.sessions_cleaned in metric discovery.

Nothing at all, with no error printed? Check OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf first, then run once with OTEL_DOTNET_SELF_DIAGNOSTICS_SINKS=stderr.

Next Steps

  • Traces: how OTel spans map to Endpoints, Tasks and Issues
  • Logs: log record mapping and severity handling
  • Metrics: supported metric types and histogram handling
  • Overview: protocol details, authentication, and a "nothing is showing up" checklist