api-versioning
API versioning strategies for ASP.NET Core. Covers Asp.Versioning library, URL segment,…
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
$ npx -y skills add codewithmukesh/dotnet-claude-kit --skill opentelemetry --agent claude-codeHow it fires
How this skill gets triggered: by you, by Claude, or both.
/opentelemetryContext preview
The summary Claude sees to decide when to auto-load this skill.
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
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".
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.
// 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
Register a metrics class as a singleton. `IMeterFactory` handles `Meter` disposal through DI.
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>();Three or fewer tags are allocation-free. For more, use `TagList`.
// 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);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.
Run the standalone Aspire Dashboard without Aspire orchestration:
API versioning strategies for ASP.NET Core. Covers Asp.Versioning library, URL segment,…
Architecture conformance check: verifies an existing codebase against its declared…
Architecture selection advisor for .NET applications. Asks structured questions about domain…
.NET Aspire for cloud-native orchestration. Covers AppHost configuration, service defaults,…
Authentication and authorization for ASP.NET Core. Covers JWT bearer tokens, OpenID Connect,…
Autonomous iteration loops for .NET: drive a broken build or failing test suite to green with…