Skip to content

OpenTelemetry guide

OpenTelemetry for .NET and ASP.NET Core

.NET has tracing built in through System.Diagnostics.Activity. OpenTelemetry collects those activities from ASP.NET Core, HttpClient and EF Core and exports them.

3 min read10 sectionsUpdated

On this page

Key points

  • AddOpenTelemetry() in Program.cs sets up tracing and metrics together.
  • ASP.NET Core and HttpClient instrumentation cover requests in and out.
  • ActivitySource is the .NET name for a tracer.
  • AddOtlpExporter reads the standard OTEL_ variables.

Install

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

Configure in Program.cs

Program.cscsharp
using OpenTelemetry.Metrics;
using OpenTelemetry.Resources;
using OpenTelemetry.Trace;

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddOpenTelemetry()
    .ConfigureResource(r => r.AddService(serviceName: "payments-api", serviceVersion: "2.7.0"))
    .WithTracing(t => t
        .AddAspNetCoreInstrumentation()
        .AddHttpClientInstrumentation()
        .AddSource("Payments")              // your own ActivitySource
        .AddOtlpExporter())
    .WithMetrics(m => m
        .AddAspNetCoreInstrumentation()
        .AddHttpClientInstrumentation()
        .AddRuntimeInstrumentation()        // needs OpenTelemetry.Instrumentation.Runtime
        .AddOtlpExporter());

var app = builder.Build();
app.MapGet("/payments/{id}", (string id) => Results.Ok());
app.Run();
bash
OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4318
OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf
OTEL_RESOURCE_ATTRIBUTES=deployment.environment.name=production

Custom spans with ActivitySource

RefundService.cscsharp
using System.Diagnostics;

public class RefundService
{
    private static readonly ActivitySource Source = new("Payments");

    public async Task RefundAsync(string paymentId)
    {
        using var activity = Source.StartActivity("refund payment");
        activity?.SetTag("payment.id", paymentId);
        // ...
    }
}

The source name must be registered with AddSource, or its activities are not exported. Entity Framework Core and SqlClient have their own instrumentation packages, which add a span per database command.

Send it to VitalRix

Directly. VitalRix accepts OTLP over HTTP with protobuf or JSON, which is what the .NET exporter sends. Instead of a Collector at localhost:4318, point the exporter at VitalRix with the per-signal endpoints and your API key. Create the key in VitalRix under Settings, API keys, with trace, metric and log ingestion.

bash
export OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf
export OTEL_EXPORTER_OTLP_TRACES_ENDPOINT=https://api.vitalrix.com/api/v1/traces/otlp/v1/traces
export OTEL_EXPORTER_OTLP_METRICS_ENDPOINT=https://api.vitalrix.com/api/v1/metrics/otlp/v1/metrics
export OTEL_EXPORTER_OTLP_LOGS_ENDPOINT=https://api.vitalrix.com/api/v1/logs/otlp/v1/logs
export OTEL_EXPORTER_OTLP_HEADERS=x-api-key=your_api_key

Through a Collector. Run an OpenTelemetry Collector next to your app, or as a shared service, when the SDK exports over gRPC or you want one place for batching, sampling and retries. It receives from the SDK and forwards to VitalRix with your key.

otel-collector.yamlyaml
receivers:
  otlp:
    protocols:
      grpc: { endpoint: 0.0.0.0:4317 }
      http: { endpoint: 0.0.0.0:4318 }
processors:
  memory_limiter: { check_interval: 1s, limit_mib: 512 }
  batch: {}
exporters:
  otlphttp/vitalrix:
    traces_endpoint: ${env:VITALRIX_API}/api/v1/traces/otlp/v1/traces
    metrics_endpoint: ${env:VITALRIX_API}/api/v1/metrics/otlp/v1/metrics
    headers:
      x-api-key: ${env:VITALRIX_KEY}
service:
  pipelines:
    traces:  { receivers: [otlp], processors: [memory_limiter, batch], exporters: [otlphttp/vitalrix] }
    metrics: { receivers: [otlp], processors: [memory_limiter, batch], exporters: [otlphttp/vitalrix] }
bash
docker run -d --name otel-collector -p 4317:4317 -p 4318:4318 \
  -e VITALRIX_API=https://api.vitalrix.com -e VITALRIX_KEY=your_api_key \
  -v "$PWD/otel-collector.yaml:/etc/otelcol-contrib/config.yaml" \
  otel/opentelemetry-collector-contrib:latest

Zero-code option

OpenTelemetry .NET automatic instrumentation can instrument an app without code changes, using environment variables and a startup hook. It suits apps you cannot rebuild; for apps you own, the code-based setup above is easier to reason about and version.

Check that it works

  1. Send a few requests to the app.
  2. In VitalRix, open APM: payments-api appears in the service catalog within a minute, with request rate, error rate and p95.
  3. Open an endpoint and then one request to see its trace waterfall, including database spans.
  4. If nothing arrives, check the exporter's (or the Collector's) logs for export errors: 401 means the key or header is wrong, 402 that a new host is over the plan's APM host allowance. The packages have a check command that sends one test log.

Add service.version so new releases appear as deploy markers, and put the trace ID in your logs so each trace shows its log lines. See APM and logs, metrics and traces.

Frequently asked questions

Does it support .NET Framework?

Some instrumentation supports .NET Framework 4.6.2 and later, but the best coverage is on modern .NET. Check each package’s supported targets.

Why are my custom spans missing?

The ActivitySource name is not registered with AddSource, or StartActivity returned null because no listener was attached when it ran.

  • .NET performance monitoring: Monitor .NET and ASP.NET Core apps: request latency, GC and allocation rate, thread pool starvation, HttpClient and EF Core calls, with dotnet-counters.
  • OpenTelemetry for FastAPI: Trace a FastAPI service with OpenTelemetry: instrument the app, async database drivers and httpx, run uvicorn workers correctly and export.
  • OpenTelemetry for Go: Instrument a Go service with OpenTelemetry: set up the tracer provider, wrap net/http with otelhttp, pass context everywhere and export the spans.
  • OpenTelemetry for PHP and Laravel: Trace a Laravel app with OpenTelemetry: install the PHP extension and auto-instrumentation packages, configure PHP-FPM and trace queries.
  • OpenTelemetry for NestJS: Trace a NestJS service with OpenTelemetry: load the SDK before Nest boots, instrument HTTP, Express and NestJS core, and export JSON to VitalRix.
  • OpenTelemetry for Flask: Instrument a Flask app with OpenTelemetry, in code or with zero code: trace routes, SQLAlchemy and outgoing calls, and export to VitalRix.

Watch your own site and services with VitalRix

Uptime checks, APM, logs, real-user monitoring, alerts and status pages in one place. Every product has a free tier and no credit card is needed.