OpenTelemetry in ASP.NET Core on .NET 10: the three signals and how logs carry TraceId/SpanId, AddOpenTelemetry with WithTracing, WithMetrics and WithLogging, resource attributes, built-in ASP.NET Core and HttpClient instrumentation and meters, UseOtlpExporter vs the Azure Monitor distro (UseAzureMonitor, rate-limited sampling default since 1.5), head versus tail sampling in the Collector, and cost control.
OpenTelemetry gives you three correlated signals: traces (a span per operation, linked by trace id), metrics (cheap aggregated counters and histograms) and logs (events that carry the TraceId and SpanId of the span they were written in).
In .NET the runtime already emits Activity and Meter data; you call AddOpenTelemetry() with WithTracing, WithMetrics and WithLogging, set a resource (service.name), and choose an exporter: UseOtlpExporter() for any OTLP back end or Collector (endpoint from OTEL_EXPORTER_OTLP_ENDPOINT or options), or the Azure Monitor distro (UseAzureMonitor()) for Application Insights.
For cost: metrics for rates and latency (never sampled), sampled traces (the distro now defaults to a rate-limited sampler of 5 traces per second, which adapts the kept percentage to load; you can change the rate or switch to a fixed SamplingRatio), level-filtered logs, and tail sampling in a Collector, configured with policies to keep errors and slow traces. The trade-off is completeness versus ingestion cost.
"I think of OpenTelemetry as three signals sharing one context. Traces tell me what happened to a single request across services: each operation is a span, and spans share a trace id. Metrics tell me how the system behaves in aggregate: request rate, error rate, latency histograms, GC and thread pool counters, and they're cheap because they're pre-aggregated. Logs are the detailed events, and with OpenTelemetry every log record carries the current trace id and span id, so from a slow trace I can jump straight to the logs written during it.
In .NET most of the instrumentation is already built in: ASP.NET Core, HttpClient, SqlClient and the Azure SDKs emit
Activityobjects andMeterinstruments. InProgram.csI callAddOpenTelemetry(), set the resource so everything is labelled with the service name and environment, turn on tracing, metrics and logging, add my ownActivitySourceandMeternames, and pick an exporter.UseOtlpExporter()sends everything over OTLP to a Collector, the Aspire dashboard locally, or a vendor. On Azure I usually use the Azure Monitor distro,UseAzureMonitor(), which wires the same SDK to Application Insights. For example, at [company] we [moved from the classic Application Insights SDK to the distro and pointed local development at the Aspire dashboard, so developers saw the same traces locally as in production].Sampling is where seniority shows. Metrics aren't sampled, so they're my source of truth for rates and percentiles. Traces are sampled at the head with a parent-based sampler so a trace is kept or dropped as a whole across services. The Azure Monitor distro changed its default in 1.5 to a rate limit of five traces per second, which surprises teams who expect 100%. If I need every failed or slow request, I add a Collector with tail sampling. And logs I control by level, not by sampling. The mistake I see is turning everything to 100% and Debug, then cutting it randomly when the bill arrives. Decide what each signal is for, then size it."
| Signal | Answers | Cost driver | Sample? |
|---|---|---|---|
| Metrics | Is it healthy? Rate, errors, latency percentiles | Number of time series (dimensions) | No |
| Traces | Where did this request spend its time? | Spans per request × requests | Yes |
| Logs | What exactly happened, with details? | Lines × size | Filter by level, not sampling |
| Exporter | Goes to | Fits | Watch |
|---|---|---|---|
UseOtlpExporter() |
Collector, Aspire dashboard, Grafana, Datadog, Elastic, Honeycomb | Vendor-neutral, multi-cloud | You run or buy the back end |
UseAzureMonitor() (Azure.Monitor.OpenTelemetry.AspNetCore) |
Application Insights / Log Analytics | Azure-hosted services | Default rate-limited sampling, per-GB ingestion |
| Collector in between | Anywhere, with processing | Tail sampling, redaction, fan-out | Another component to operate |
| Approach | How | Keeps | Cost |
|---|---|---|---|
| Head, ratio | ParentBasedSampler(TraceIdRatioBasedSampler(0.1)) |
10% of whole traces | Errors sampled at the same rate |
| Head, rate-limited | Distro default (5/s) | Fixed volume regardless of load | Low-traffic paths still kept |
| Tail | Collector tail_sampling processor |
All errors, slow traces, a % of the rest | Collector must buffer whole traces |
For an API at [1,500] requests a second, moving from 100% traces to the distro's rate-limited sampler plus tail sampling for errors in a Collector cut Application Insights ingestion from about [60] GB to [9] GB a day, while dashboards built on metrics stayed exact and every 5xx trace was still kept.
Checks whether the candidate can design production telemetry with OpenTelemetry, not just paste a set-up snippet.
Green flags
Activity and Meter and what instrumentation adds.Red flags
ASP.NET Core / HttpClient / SqlClient / Azure SDK / your code
│ Activity (System.Diagnostics) │ Meter (System.Diagnostics.Metrics) │ ILogger
▼ ▼ ▼
TracerProvider MeterProvider LoggerProvider
(sampler, processors) (views, aggregation) (processors)
│ │ │
└───────────────────────────────────┬───────────────────────────────────┘
▼
batch export processors (per signal)
│
┌──────────────────────────┼──────────────────────────┐
▼ ▼ ▼
OTLP exporter Azure Monitor exporter Console exporter
│ │
OTel Collector Application Insights
(tail sampling, redaction) (Australia East workspace)
.NET does not need a separate tracing API: Activity is the span and ActivitySource is the tracer. OpenTelemetry subscribes through ActivityListener and MeterListener.
Since .NET 8, ASP.NET Core and HttpClient publish metrics natively (meters such as Microsoft.AspNetCore.Hosting with http.server.request.duration, and System.Net.Http). .NET 9 added built-in runtime metrics (System.Runtime meter). The OpenTelemetry instrumentation packages add richer span attributes and filtering on top.
The OpenTelemetry logging provider reads Activity.Current when a log is written and stamps the record with TraceId, SpanId and TraceFlags. In Application Insights these appear as operation_Id and operation_ParentId, so the end-to-end transaction view shows the logs under each span. Logs written outside any activity (start-up, background loops without your own activity) have no trace id, so start an activity per unit of work in workers.
ParentBasedSampler respects the caller's sampled flag in traceparent, so a trace is all-or-nothing across services.options.SamplingRatio with TracesPerSecond = null to go back to a fixed percentage, or use OTEL_TRACES_SAMPLER environment variables.service.name, service.version, deployment.environment and the cloud role instance identify where data came from. Every metric dimension multiplies time series: never use user ids or full URLs as metric tags; route templates (/orders/{id}) are fine.
For Australian workloads that hold personal information, put the Log Analytics workspace behind Application Insights in Australia East or Southeast, and remember OpenTelemetry attributes can carry personal data: redact before export (Collector processors or Microsoft.Extensions.Compliance.Redaction).
mcr.microsoft.com/dotnet/aspire-dashboard) and point UseOtlpExporter() at it; view traces, metrics and structured logs together.HttpClient and confirm both appear in one trace.SamplingRatio = 0.1 and load test with k6; compare request counts in traces versus the http.server.request.duration metric.ActivitySource in a background worker and check its logs now have trace ids.tail_sampling processor keeping status_code ERROR, and verify every failing request is kept.One registration for all three signals, with OTLP locally and Azure Monitor in Azure.
// Program.cs
// Packages: OpenTelemetry.Extensions.Hosting, OpenTelemetry.Instrumentation.AspNetCore,
// OpenTelemetry.Instrumentation.Http, OpenTelemetry.Exporter.OpenTelemetryProtocol,
// Azure.Monitor.OpenTelemetry.AspNetCore
using System.Diagnostics;
using System.Diagnostics.Metrics;
using Azure.Monitor.OpenTelemetry.AspNetCore;
using OpenTelemetry.Metrics;
using OpenTelemetry.Resources;
using OpenTelemetry.Trace;
var builder = WebApplication.CreateBuilder(args);
var otel = builder.Services.AddOpenTelemetry()
.ConfigureResource(r => r.AddService("orders-api", serviceVersion: "1.4.2")
.AddAttributes([new("deployment.environment", builder.Environment.EnvironmentName)]))
.WithTracing(t => t
.AddAspNetCoreInstrumentation(o => o.Filter = ctx => ctx.Request.Path != "/healthz") // no health-probe noise
.AddHttpClientInstrumentation()
.AddSource(OrdersTelemetry.SourceName))
.WithMetrics(m => m
.AddAspNetCoreInstrumentation()
.AddHttpClientInstrumentation()
.AddRuntimeInstrumentation()
.AddMeter(OrdersTelemetry.MeterName))
.WithLogging(configureOptions: o => o.IncludeScopes = true);
if (builder.Configuration["APPLICATIONINSIGHTS_CONNECTION_STRING"] is { Length: > 0 })
{
// Azure: distro defaults to rate-limited sampling (5 traces/s); make the choice explicit
otel.UseAzureMonitor(o => o.TracesPerSecond = 5);
}
else
{
// Local / other back ends: OTEL_EXPORTER_OTLP_ENDPOINT, e.g. the Aspire dashboard
otel.UseOtlpExporter();
}
builder.Services.AddSingleton<OrdersTelemetry>();
var app = builder.Build();
app.MapPost("/orders", (OrdersTelemetry telemetry, ILogger<Program> logger) =>
{
using var activity = OrdersTelemetry.Source.StartActivity("PlaceOrder");
telemetry.OrdersPlaced.Add(1, new KeyValuePair<string, object?>("channel", "web")); // low-cardinality tag
logger.LogInformation("Order placed"); // carries TraceId/SpanId of PlaceOrder
return TypedResults.Accepted("/orders/1");
});
app.MapGet("/healthz", () => TypedResults.Ok());
app.Run();
public sealed class OrdersTelemetry(IMeterFactory meterFactory)
{
public const string SourceName = "Shop.Orders";
public const string MeterName = "Shop.Orders";
public static readonly ActivitySource Source = new(SourceName);
public Counter<long> OrdersPlaced { get; } = meterFactory.Create(MeterName).CreateCounter<long>("shop.orders.placed");
}
service.name. Why it is wrong: Data shows up as unknown_service, and application maps are useless. Instead: Set resource attributes for name, version and environment./healthz in ASP.NET Core instrumentation.Activity. Why it is wrong: Their logs have no trace id and can't be correlated. Instead: Start an activity per message or job from your own ActivitySource.I design telemetry around questions: metrics answer "is it broken and for how many", traces answer "where", logs answer "why". That decides the budget: metrics complete and cheap, traces sampled but whole, logs filtered by level with redaction. OpenTelemetry's real value is that this design survives a vendor change; the exporter is a line in Program.cs or a Collector config.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Azure Monitor distro | Azure-hosted, Application Insights users | Per-GB ingestion, distro defaults to learn | Multi-cloud or non-Azure back end |
| OTLP direct to vendor | Small estate, one back end | Vendor lock-in at the back end only | Need tail sampling or redaction centrally |
| OTLP via Collector | Many services, tail sampling, redaction, fan-out | Operating the Collector | Single small service |
| 100% traces | Low traffic, early life of a service | Scales linearly with load | High-traffic APIs |
Two mechanisms work together.
using (logger.BeginScope(new Dictionary<string, object> { ["OrderId"] = id })) adds properties to every log inside the block, flowing across await via AsyncLocal. ASP.NET Core already opens a scope per request with RequestId and RequestPath.Activity whose trace id comes from the incoming W3C traceparent header or is created new. With ActivityTrackingOptions (on by default in the Generic Host) every log carries TraceId and SpanId. HttpClient propagates traceparent automatically; message queues need it copied into message properties (the Azure Service Bus SDK does this).So the trace id is your correlation id; add business ids as properties. The trade-off: custom correlation headers are easy but don't interoperate with tracing tools.
Your code always logs through ILogger<T>; the choice is what sits underneath.
AddSerilog). Destinations are sinks (Seq, files, Elastic, OTLP); enrichers add properties such as machine name or user id. It has rich destructuring and a bootstrap logger for start-up failures.UseNLog) uses targets and layouts, configured in nlog.config, popular in older enterprise estates.AddOpenTelemetry().WithLogging() exports to OTLP or Azure Monitor, with logs correlated to traces and metrics.For a new .NET 10 service on Azure I'd start with built-in + OpenTelemetry; I'd keep Serilog or NLog where a team already relies on their sinks. The trade-off is fewer moving parts versus richer formatting and sink choice.
How to tell it (STAR)
**S:** At [company] a routine package upgrade on our payments API made most failed requests disappear from Application Insights, and support couldn't find a customer's failed payment. **T:** I needed to explain the gap and make sure we never lost error traces again. **A:** I compared trace counts with the request-duration metric, saw a constant ratio, and traced it to the distro's new rate-limited sampling default. I raised the limit straight away, then added a Collector with tail sampling to keep every error and slow trace, and moved our dashboards and alerts onto metrics. **R:** Every 5xx trace has been kept since, ingestion stayed about [40%] below the old 100% level, and our alerts became independent of sampling.
Last updated 23 Nov 2026.