Skip to main content
skill CX Codex

opentelemetry · codewithmukesh — Claude Code skill: what it does, how to install

Configures OpenTelemetry traces, metrics, and logs in .NET 10 applications using OTLP export and IMeterFactory.

Install into Claude Code · Skills CLI (Vercel) All methods and platforms ↓
npx skills add codewithmukesh/dotnet-claude-kit --skill opentelemetry -a claude-code
Open on GitHub

What opentelemetry does

This skill guides coding agents through setting up OpenTelemetry for .NET 10 apps. It bundles traces, metrics, and logs into a single AddOpenTelemetry() setup with unified UseOtlpExporter(). Mixing per-signal exporter calls with UseOtlpExporter throws a NotSupportedException.

For metrics, it enforces using IMeterFactory via dependency injection instead of instantiating new Meter(), preventing memory leaks. Up to three metric tags remain allocation-free; four or more require TagList. For distributed tracing, it uses ActivitySource with null-safe operators because StartActivity() returns null when listeners are absent.

What it helps with

  • configure .NET 10 distributed tracing, metrics, and logs via OTLP
  • prevent memory leaks by creating metrics with IMeterFactory
  • instrument custom spans using ActivitySource
  • configure local telemetry collection for Aspire Dashboard

Example prompts for the agent

  • Configure OpenTelemetry for my .NET 10 API with OTLP export
  • Create custom metrics using IMeterFactory with counter and histogram
  • Add an ActivitySource to trace order processing workflows

How to install opentelemetry

1Skills CLI (Vercel)

npx skills add codewithmukesh/dotnet-claude-kit --skill opentelemetry -a claude-code

2Manually: put the files in place

~/.claude/skills/opentelemetry/SKILL.md

Copy the whole skill folder; for one project use .claude/skills/opentelemetry/

Step by step, with commands for each platform: How to install skills in Claude Code: five ways

Questions about opentelemetry

How to install opentelemetry in Claude Code?

Run npx skills add codewithmukesh/dotnet-claude-kit --skill opentelemetry -a claude-code.

What does the opentelemetry skill do?

It provides patterns for .NET 10 observability. It covers three signals under OTLP, metric instruments via IMeterFactory, and custom activities.

Why does the skill disallow creating Meter instances with new?

Instantiating Meter objects directly causes memory leaks. IMeterFactory manages lifecycle through dependency injection and cleans up resources properly.

Source text

SKILL.md · MIT
---
name: opentelemetry
description: >
  OpenTelemetry observability for .NET 10 applications. Covers traces, metrics,
  and logs using the OpenTelemetry SDK with OTLP export. Includes custom
  ActivitySource, IMeterFactory metrics, resource configuration, and Aspire
  Dashboard integration.
  Load this skill when setting up distributed tracing, custom metrics, OTLP
  export, or when the user mentions "OpenTelemetry", "OTLP", "traces", "spans",
  "Activity", "ActivitySource", "metrics", "IMeterFactory", "Meter", "Counter",
  "Histogram", "Gauge", "telemetry", "observability", "distributed tracing",
  "OTEL", or "Aspire Dashboard".
---

# OpenTelemetry

## Core Principles

1. **Three pillars, one setup** — Configure traces, metrics, and logs through a single `AddOpenTelemetry()` call. Use `UseOtlpExporter()` for cross-cutting export to any OTLP-compatible backend.
2. **Use `IMeterFactory` for metrics** — Never create `Meter` instances with `new`. The factory manages lifetime through DI and prevents leaks.
3. **Null-safe activities** — `StartActivity()` returns `null` when no listener is attached. Always use `?.` when setting tags or events.
4. **Environment variables over code** — Use `OTEL_EXPORTER_OTLP_ENDPOINT` and `OTEL_SERVICE_NAME` so deployments control telemetry routing without code changes.
5. **Low-cardinality metric tags** — Keep metric tag combinations under ~1000 per instrument. Use span attributes or logs for high-cardinality data like user IDs or request IDs.

## Patterns

### Full Setup with All Three Signals

```csharp
// Program.cs
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddOpenTelemetry()
    .ConfigureResource(resource => resource
        .AddService(
            serviceName: builder.Environment.ApplicationName,
            serviceVersion: "1.0.0"))
    .WithTracing(tracing => tracing
        .AddAspNetCoreInstrumentation()
        .AddHttpClientInstrumentation()
        .AddEntityFrameworkCoreInstrumentation()
        .AddSource("MyApp.Orders"))
    .WithMetrics(metrics => metrics
        .AddAspNetCoreInstrumentation()
        .AddHttpClientInstrumentation()
        .AddRuntimeInstrumentation()
        .AddMeter("MyApp.Orders"))
    .WithLogging()             // no per-signal exporter here —
    .UseOtlpExporter();        // UseOtlpExporter covers all three signals

// UseOtlpExporter replaces per-signal AddOtlpExporter calls. Never combine
// the two — mixing them throws NotSupportedException (see Anti-patterns).
```

The OTLP endpoint defaults to `http://localhost:4317` (gRPC). Override via:
```
OTEL_EXPORTER_OTLP_ENDPOINT=http://collector:4317
OTEL_SERVICE_NAME=MyApp.Api
```

### Custom Metrics with IMeterFactory

Register a metrics class as a singleton. `IMeterFactory` handles `Meter` disposal through DI.

```csharp
public sealed class OrderMetrics
{
    private readonly Counter<int> _ordersCreated;
    private readonly Histogram<double> _orderDuration;
    private readonly UpDownCounter<int> _activeOrders;
    private readonly Gauge<double> _queueDepth;

    public OrderMetrics(IMeterFactory meterFactory)
    {
        var meter = meterFactory.Create("MyApp.Orders");

        _ordersCreated = meter.CreateCounter<int>(
            "myapp.orders.created", "{orders}", "Number of orders created");

        _orderDuration = meter.CreateHistogram<double>(
            "myapp.orders.duration", "s", "Order processing duration",
            advice: new InstrumentAdvice<double>
            {
                HistogramBucketBoundaries = [0.01, 0.05, 0.1, 0.5, 1, 5, 10]
            });

        _activeOrders = meter.CreateUpDownCounter<int>(
            "myapp.orders.active", "{orders}", "Currently active orders");

        _queueDepth = meter.CreateGauge<double>(
            "myapp.orders.queue_depth", "{items}", "Current queue depth");
    }

    public void OrderCreated() => _ordersCreated.Add(1);
    public void RecordDuration(double seconds) => _orderDuration.Record(seconds);
    public void OrderStarted() => _activeOrders.Add(1);
    public void OrderCompleted() => _activeOrders.Add(-1);
    public void SetQueueDepth(double depth) => _queueDepth.Record(depth);
}

// Registration
builder.Services.AddSingleton<OrderMetrics>();
```

### Multi-Dimensional Metric Tags

Three or fewer tags are allocation-free. For more, use `TagList`.

```csharp
// Allocation-free (3 or fewer tags)
_ordersCreated.Add(1,
    new KeyValuePair<string, object?>("order.type", "standard"),
    new KeyValuePair<string, object?>("payment.method", "credit_card"));

// 4+ tags — use TagList to avoid allocations
var tags = new TagList
{
    { "order.type", "standard" },
    { "payment.method", "credit_card" },
    { "region", "us-east" },
    { "priority", "high" }
};
_ordersCreated.Add(1, tags);
```

### Custom ActivitySource for Distributed Tracing

```csharp
public sealed class OrderService(ILogger<OrderService> logger)
{
    private static readonly ActivitySource Source = new("MyApp.Orders");

    public async Task<Order> ProcessOrderAsync(CreateOrderRequest request, CancellationToken ct)
    {
        using var activity = Source.StartActivity("ProcessOrder", ActivityKind.Internal);
        activity?.SetTag("order.customer_id", request.CustomerId);

        try
        {
            await ValidateOrder(request, ct);
            activity?.AddEvent(new ActivityEvent("OrderValidated"));

            var order = await SaveOrder(request, ct);
            activity?.SetTag("order.id", order.Id.ToString());
            activity?.SetStatus(ActivityStatusCode.Ok);
            return order;
        }
        catch (Exception ex)
        {
            activity?.SetStatus(ActivityStatusCode.Error, ex.Message);
            activity?.RecordException(ex);
            throw;
        }
    }
}
```

Register the source: `.AddSource("MyApp.Orders")` in the tracing builder.

### Aspire Dashboard for Local Development

Run the standalone Aspire Dashboard without Aspire orchestration:

```bash
docker run --rm -it -p 18888:18888 -p 4317:18889 \
    mcr.microsoft.com/dotnet/aspire-dashboard:latest
```

Then point your app at it:
```
OTEL_EXPORTER_OTLP_ENDPOINT=http://localhost:4317
```

Dashboard UI is at `http://localhost:18888`.

### Source-Generated Logging with OTel

For maximum performance, use `[LoggerMessage]` — eliminates boxing and allocations.

```csharp
public partial class OrderService(ILogger<OrderService> logger)
{
    [LoggerMessage(Level = LogLevel.Information,
        Message = "Processing order {OrderId} for customer {CustomerId}")]
    partial void LogOrderProcessing(Guid orderId, Guid customerId);
}
```

OpenTelemetry logging automatically includes `TraceId` and `SpanId` when an `Activity` is current.

## Anti-patterns

### Don't Create Meters Per Request

```csharp
// BAD — new Meter per request causes memory leaks
public void HandleRequest()
{
    var meter = new Meter("MyApp");
    meter.CreateCounter<int>("requests").Add(1);
}

// GOOD — singleton via IMeterFactory
public class MyMetrics(IMeterFactory meterFactory)
{
    private readonly Counter<int> _requests =
        meterFactory.Create("MyApp").CreateCounter<int>("myapp.requests");
    public void RequestHandled() => _requests.Add(1);
}
```

### Don't Skip Null Checks on Activity

```csharp
// BAD — NullReferenceException when no listener is attached
using var activity = source.StartActivity("Work");
activity.SetTag("key", "value");

// GOOD — null-safe
activity?.SetTag("key", "value");
```

### Don't Use High-Cardinality Metric Tags

```csharp
// BAD — unbounded cardinality causes memory explosion in collectors
_counter.Add(1, new("request.id", Guid.NewGuid().ToString()));
_counter.Add(1, new("user.id", userId));

// GOOD — low-cardinality dimensions only
_counter.Add(1, new("http.method", "GET"), new("http.status_code", 200));
```

### Don't Mix UseOtlpExporter with AddOtlpExporter

```csharp
// BAD — throws NotSupportedException at runtime
builder.Services.AddOpenTelemetry()
    .UseOtlpExporter()
    .WithTracing(t => t.AddOtlpExporter());

// GOOD — use one approach
builder.Services.AddOpenTelemetry().UseOtlpExporter();
```

### Don't Forget to Register Custom Sources

```csharp
// BAD — activities silently dropped (no listener registered)
var source = new ActivitySource("MyApp.Custom");
using var activity = source.StartActivity("Work"); // null!

// GOOD — register in the tracing builder
otel.WithTracing(t => t.AddSource("MyApp.Custom"));
otel.WithMetrics(m => m.AddMeter("MyApp.Custom"));
```

## Decision Guide

| Scenario | Recommendation |
|----------|---------------|
| Full observability setup | `AddOpenTelemetry()` with all three signals + `UseOtlpExporter()` |
| Custom business metrics | `IMeterFactory` + singleton metrics class |
| Custom trace spans | `ActivitySource` + `StartActivity()` |
| Local development backend | Aspire Dashboard standalone container |
| Production backend | OTel Collector as intermediary to Grafana/Datadog/etc. |
| Sampling in production | `OTEL_TRACES_SAMPLER=parentbased_traceidratio` with 10% ratio |
| High-performance logging | `[LoggerMessage]` source generator |
| Metric tag cardinality | Max ~1000 combinations per instrument |
| Environment configuration | `OTEL_*` env vars (also work via `appsettings.json`) |

© codewithmukesh · MIT · codewithmukesh/dotnet-claude-kit

Similar skills

Everything for Backend and APIs →

opentelemetry by other authors comes first.

opentelemetry grafana A skill that walks you through instrumenting an app with OpenTelemetry and sending metrics, logs and traces to Grafana Cloud or self-hosted Mimir, Loki and Tempo. CX Codex +1 6,100installs opentelemetry devops-skills A skill that wires OpenTelemetry into your services so traces, metrics and logs share one format and one backend. CX Codex +1 339installs opentelemetry Claude MPM Team A skill with OpenTelemetry patterns: traces, metrics, logs, context propagation and Collector pipelines. Useful when a service needs instrumenting instead of guesswork. CX Codex +1 635installs opentelemetry-net-instrumentation Aaronontheweb A skill that guides OpenTelemetry instrumentation in .NET code: traces, metrics and logs. Useful when you add telemetry to a library or an app. CX Codex +1 408installs golang-observability-opentelemetry Claude MPM Team A skill for instrumenting Go services: OpenTelemetry for distributed tracing, Prometheus for metrics, slog for structured logging. CX Codex +1 409installs observability-and-instrumentation addyosmani Instruments code with structured logs, RED and USE metrics, and distributed tracing. Use it when shipping features to production so issues are diagnosable. CX Codex +1 54,800installs otel-instrumentation dash0 Gives your agent a rulebook for OpenTelemetry spans, metrics and logs, so telemetry answers questions instead of burning budget. CX Codex +1 972installs Observability taste f A prompt that tells an AI assistant how to wire traces, metrics and logs into a service. Handy when you ask a model to write instrumented code. GP ChatGPT ★ 174,597repo stars azure-monitor-opentelemetry-exporter-py Microsoft A skill for low-level OpenTelemetry export of traces, metrics and logs to Application Insights from Python. Useful when you run a custom telemetry pipeline. 1installs

From the same set46

health-check Grades a .NET project across eight dimensions with letter marks A–F and a rolled-up GPA. Useful at onboarding, before a release, and after a cleanup sprint. CX Codex +1 2,800installs openapi Configures native OpenAPI generation in .NET 10 without Swashbuckle. Helps the agent handle transformers, TypedResults metadata, and security schemes. CX Codex +1 2,800installs configuration Guides .NET 10 configuration with typed options, validation, and secret handling. Use it when working with appsettings files or environment variables. CX Codex +1 2,800installs scalar A skill that walks the agent through wiring Scalar into a .NET 10 app as a Swagger UI replacement, with themes, auth prefill and multiple documents. CX Codex +1 2,800installs messaging A .NET skill that walks your agent through Wolverine or MassTransit setup, the outbox pattern, sagas, and RabbitMQ or Azure Service Bus brokers. CX Codex +1 2,800installs project-structure A skill that tells your agent how to lay out a .NET solution: central package versions, shared build properties, .slnx format and naming rules. CX Codex +1 2,800installs httpclient-factory Guides AI coding agents in configuring IHttpClientFactory and typed clients in .NET 10. Useful when building resilient HTTP pipelines and preventing socket exhaustion. CX Codex +1 2,800installs de-sloppify Runs a seven-step cleanup pass for .NET code, from formatting through CancellationToken propagation. Use it before a release or after larger changes and dependency updates. CX Codex +1 2,800installs

Project sponsors

Companies that keep this analytics open
Gold sponsor

Impressions, clicks and code copies — open statistics. We keep the numbers public for the same reason NeBlask itself is public. Become a sponsor