[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7EKEMT2GDDJY29AP0HRERD3":3,"skill-same:01M7EKEMT2GDDJY29AP0HRERD3":52},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":32,"commitSha":33,"skillDirectory":34,"forksCount":14,"repositoryHtmlUrl":35,"repositoryHomepageUrl":35,"ownerHtmlUrl":36,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":37,"install":38,"resources":51},"01M7EKEMT2GDDJY29AP0HRERD3","configuring-opentelemetry-dotnet",null,"Configure OpenTelemetry distributed tracing, metrics, and logging in ASP.NET Core using the .NET OpenTelemetry SDK. Use when adding observability, setting up OTLP exporters, creating custom metrics\u002Fspans, or troubleshooting distributed trace correlation.","Mr-Nobody-Anonymous\u002FAll-skills","Mr-Nobody-Anonymous","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F184253119?v=4","01M7AEXFJHKTYQW5R0ZCQQTWFV","anonymous","01M7C00M3GQR4QKP9GZA42GFAK",0,"MIT","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fcloud\u002Fconfiguring-opentelemetry-dotnet\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: configuring-opentelemetry-dotnet\ndescription: \"Configure OpenTelemetry distributed tracing, metrics, and logging in ASP.NET Core using the .NET OpenTelemetry SDK. Use when adding observability, setting up OTLP exporters, creating custom metrics\u002Fspans, or troubleshooting distributed trace correlation.\"\ncategory: cloud\nversion: 1.0.0\ndisable-model-invocation: false\nrisk: low\nsource:\n  repository: \"microsoft\u002Fskills\"\n  commit: \"8f3b1a2c\"\n  path: \"plugins\u002Fdotnet-aspnetcore\u002Fskills\u002Fconfiguring-opentelemetry-dotnet\u002FSKILL.md\"\n  license: \"MIT\"\n  imported_at: \"2026-09-20\"\n---\n# Configuring OpenTelemetry in .NET\n\n## When to Use\n\n- Adding distributed tracing to an ASP.NET Core application\n- Setting up OpenTelemetry exporters (OTLP is the primary protocol; Jaeger accepts OTLP natively; Prometheus OTLP ingestion requires explicit opt-in)\n- Creating custom metrics or trace spans for business operations\n- Troubleshooting distributed trace context propagation across services\n\n## When Not to Use\n\n- The user wants application-level logging only (use ILogger, Serilog)\n- The user is using Application Insights SDK directly (different API)\n- The user needs APM with a commercial vendor's proprietary SDK\n\n## Inputs\n\n| Input | Required | Description |\n|-------|----------|-------------|\n| ASP.NET Core project | Yes | The application to instrument |\n| Observability backend | No | Where to export: OTLP collector, Aspire dashboard, Jaeger (accepts OTLP natively) |\n\n## Workflow\n\n### Step 1: Install the correct packages\n\n**There are many OpenTelemetry NuGet packages. Install exactly these:**\n\n```bash\n# Core SDK + ASP.NET Core instrumentation + logging integration\ndotnet add package OpenTelemetry.Extensions.Hosting\ndotnet add package OpenTelemetry.Instrumentation.AspNetCore\ndotnet add package OpenTelemetry.Instrumentation.Http\n\n# Exporter\ndotnet add package OpenTelemetry.Exporter.OpenTelemetryProtocol  # OTLP exporter for traces, metrics, AND logs\n\n# Optional — dev\u002Flocal debugging only (do NOT include in production deployments)\n# dotnet add package OpenTelemetry.Exporter.Console\n```\n\n**Do NOT install `OpenTelemetry` alone** — you need `OpenTelemetry.Extensions.Hosting` for proper DI integration.\n\n#### Optional: additional auto-instrumentation packages\n\nInstall only the packages that match the libraries your application uses:\n\n```bash\ndotnet add package OpenTelemetry.Instrumentation.SqlClient           # SQL Server queries\ndotnet add package OpenTelemetry.Instrumentation.EntityFrameworkCore  # EF Core\ndotnet add package OpenTelemetry.Instrumentation.GrpcNetClient       # gRPC calls\ndotnet add package OpenTelemetry.Instrumentation.Runtime             # GC, thread pool metrics\n```\n\n### Step 2: Configure all signals in Program.cs\n\n```csharp\nusing OpenTelemetry.Resources;\nusing OpenTelemetry.Trace;\nusing OpenTelemetry.Metrics;\nusing OpenTelemetry.Logs;\n\nvar builder = WebApplication.CreateBuilder(args);\n\nbuilder.Services.AddOpenTelemetry()\n    .ConfigureResource(resource => resource\n        .AddService(serviceName: builder.Environment.ApplicationName))\n    .WithTracing(tracing => tracing\n        .AddAspNetCoreInstrumentation(options =>\n        {\n            \u002F\u002F Filter out health check endpoints from traces\n            options.Filter = httpContext =>\n                !httpContext.Request.Path.StartsWithSegments(\"\u002Fhealthz\");\n        })\n        .AddHttpClientInstrumentation(options =>\n        {\n            options.RecordException = true;\n        })\n        \u002F\u002F Optional: add SQL instrumentation if using SqlClient directly\n        \u002F\u002F .AddSqlClientInstrumentation(options =>\n        \u002F\u002F {\n        \u002F\u002F     options.SetDbStatementForText = true;\n        \u002F\u002F     options.RecordException = true;\n        \u002F\u002F })\n        \u002F\u002F Custom activity sources (must match ActivitySource names in your code)\n        .AddSource(\"MyApp.Orders\")\n        .AddSource(\"MyApp.Payments\")\n        .AddSource(\"MyApp.Messaging\"))\n    .WithMetrics(metrics => metrics\n        .AddAspNetCoreInstrumentation()\n        .AddHttpClientInstrumentation()\n        \u002F\u002F Optional: .AddRuntimeInstrumentation() for GC and thread pool metrics\n        \u002F\u002F   (requires OpenTelemetry.Instrumentation.Runtime package)\n        \u002F\u002F Custom meters (must match Meter names in your code)\n        .AddMeter(\"MyApp.Metrics\"))\n    .WithLogging(logging =>\n    {\n        logging.IncludeScopes = true;\n        \u002F\u002F logging.IncludeFormattedMessage = true;  \u002F\u002F Enable if you need the formatted message string in log exports\n    })\n    \u002F\u002F Single OTLP exporter for all signals — reads OTEL_EXPORTER_OTLP_ENDPOINT\n    \u002F\u002F env var (defaults to http:\u002F\u002Flocalhost:4317). Override via environment variable\n    \u002F\u002F or appsettings.json configuration.\n    .UseOtlpExporter();\n```\n\n### Step 3: Understanding log–trace correlation\n\nThe `.WithLogging()` call in Step 2 integrates ILogger with OpenTelemetry:\n\n- Each log entry automatically includes TraceId and SpanId for correlation with traces\n- The service resource from `.ConfigureResource()` propagates to logs automatically\n- `UseOtlpExporter()` applies to logs alongside traces and metrics\n- No additional packages or separate `SetResourceBuilder` call needed\n\n### Step 4: Create custom spans (Activities) for business operations\n\n```csharp\nusing System.Diagnostics;\nusing Microsoft.Extensions.Logging;\n\npublic class OrderService\n{\n    \u002F\u002F Create an ActivitySource matching what you registered in Step 2\n    private static readonly ActivitySource ActivitySource = new(\"MyApp.Orders\");\n    private readonly ILogger\u003COrderService> _logger;\n\n    public OrderService(ILogger\u003COrderService> logger) => _logger = logger;\n\n    public async Task\u003COrder> ProcessOrderAsync(CreateOrderRequest request)\n    {\n        \u002F\u002F Start a new span\n        using var activity = ActivitySource.StartActivity(\"ProcessOrder\");\n\n        \u002F\u002F Add attributes (tags) to the span\n        activity?.SetTag(\"order.customer_id\", request.CustomerId);\n        activity?.SetTag(\"order.item_count\", request.Items.Count);\n\n        try\n        {\n            \u002F\u002F Child span for validation\n            using (var validationActivity = ActivitySource.StartActivity(\"ValidateOrder\"))\n            {\n                await ValidateOrderAsync(request);\n                validationActivity?.SetTag(\"validation.result\", \"passed\");\n            }\n\n            \u002F\u002F Child span for payment\n            using (var paymentActivity = ActivitySource.StartActivity(\"ProcessPayment\",\n                ActivityKind.Client))  \u002F\u002F Client = outgoing call\n            {\n                paymentActivity?.SetTag(\"payment.method\", request.PaymentMethod);\n                await ProcessPaymentAsync(request);\n            }\n\n            var order = new Order { Id = Guid.NewGuid(), CustomerId = request.CustomerId, Status = \"Completed\" };\n\n            activity?.SetTag(\"order.status\", \"completed\");\n            activity?.SetStatus(ActivityStatusCode.Ok);\n\n            return order;\n        }\n        catch (Exception ex)\n        {\n            activity?.SetStatus(ActivityStatusCode.Error, ex.Message);\n            \u002F\u002F Log via ILogger — OpenTelemetry captures this with trace correlation.\n            \u002F\u002F Prefer logging over activity.RecordException() as OTel is deprecating\n            \u002F\u002F span events for exception recording in favor of log-based exceptions.\n            _logger.LogError(ex, \"Order processing failed for customer {CustomerId}\", request.CustomerId);\n            throw;\n        }\n    }\n}\n```\n\n**Critical: `ActivitySource` name must match `AddSource(\"...\")` in configuration.** Unmatched sources are silently ignored — this is the #1 debugging issue.\n\n### Step 5: Create custom metrics\n\nUse `IMeterFactory` (injected via DI) to create meters — this ensures proper lifetime management and testability.\n\n```csharp\nusing System.Diagnostics;\nusing System.Diagnostics.Metrics;\n\npublic class OrderMetrics\n{\n    private readonly Counter\u003Clong> _ordersProcessed;\n    private readonly Histogram\u003Cdouble> _orderProcessingDuration;\n    private readonly UpDownCounter\u003Cint> _activeOrders;\n\n    public OrderMetrics(IMeterFactory meterFactory)\n    {\n        \u002F\u002F Meter name must match AddMeter(\"...\") in configuration\n        var meter = meterFactory.Create(\"MyApp.Metrics\");\n\n        \u002F\u002F Counter — use for things that only go up\n        _ordersProcessed = meter.CreateCounter\u003Clong>(\n            \"orders.processed\", \"orders\", \"Total orders successfully processed\");\n\n        \u002F\u002F Histogram — use for measuring distributions (latency, sizes)\n        _orderProcessingDuration = meter.CreateHistogram\u003Cdouble>(\n            \"orders.processing_duration\", \"ms\", \"Time to process an order\");\n\n        \u002F\u002F UpDownCounter — use for things that go up AND down\n        _activeOrders = meter.CreateUpDownCounter\u003Cint>(\n            \"orders.active\", \"orders\", \"Currently processing orders\");\n    }\n\n    public void RecordOrderProcessed(string region, double durationMs)\n    {\n        \u002F\u002F Tags enable dimensional filtering (by region, status, etc.)\n        var tags = new TagList\n        {\n            { \"region\", region },\n            { \"order.type\", \"standard\" }\n        };\n\n        _ordersProcessed.Add(1, tags);\n        _orderProcessingDuration.Record(durationMs, tags);\n    }\n}\n```\n\nRegister `OrderMetrics` in DI:\n\n```csharp\nbuilder.Services.AddSingleton\u003COrderMetrics>();\n```\n\n### Step 6: Configure context propagation for distributed scenarios\n\nTrace context propagation is automatic for HTTP calls when using `AddHttpClientInstrumentation()`. For non-HTTP scenarios:\n\n```csharp\nusing System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing OpenTelemetry.Context.Propagation;\n\n\u002F\u002F ActivitySource should be static — register via .AddSource(\"MyApp.Messaging\") in Step 2\nprivate static readonly ActivitySource MessageSource = new(\"MyApp.Messaging\");\n\n\u002F\u002F Manual context propagation (e.g., across message queues)\n\u002F\u002F On the SENDING side:\nvar propagator = Propagators.DefaultTextMapPropagator;\nvar activityContext = Activity.Current?.Context ?? default;\nvar context = new PropagationContext(activityContext, Baggage.Current);\nvar carrier = new Dictionary\u003Cstring, string>();\n\npropagator.Inject(context, carrier, (dict, key, value) => dict[key] = value);\n\u002F\u002F Send carrier dictionary as message headers\n\n\u002F\u002F On the RECEIVING side:\nvar parentContext = propagator.Extract(default, carrier,\n    (dict, key) => dict.TryGetValue(key, out var value) ? new[] { value } : Array.Empty\u003Cstring>());\n\nBaggage.Current = parentContext.Baggage;\nusing var activity = MessageSource.StartActivity(\"ProcessMessage\",\n    ActivityKind.Consumer,\n    parentContext.ActivityContext);  \u002F\u002F Links to parent trace!\n```\n\n## Validation\n\n- [ ] Traces appear in the observability backend (Jaeger, Aspire dashboard, etc.)\n- [ ] HTTP requests automatically create spans with correct verb, URL, status code\n- [ ] Custom `ActivitySource` names match `AddSource()` registrations\n- [ ] Custom `Meter` names match `AddMeter()` registrations\n- [ ] Logs include TraceId and SpanId for correlation\n- [ ] Health check endpoints are filtered from traces\n- [ ] Exception details appear on error spans\n\n## Common Pitfalls\n\n| Pitfall | Solution |\n|---------|----------|\n| `ActivitySource.StartActivity` returns null | Source name doesn't match any `AddSource()` — names must match exactly |\n| Traces not appearing in exporter | Check OTLP endpoint: gRPC uses port 4317, HTTP uses 4318 |\n| Missing HTTP client spans | Ensure `AddHttpClientInstrumentation()` is registered; it works for both `IHttpClientFactory`\u002FDI and `new HttpClient()` (use `IHttpClientFactory` for lifetime management) |\n| High cardinality tags | Don't use user IDs, request IDs, or UUIDs as metric tags — explodes storage |\n| OTLP gRPC vs HTTP mismatch | Default is gRPC (port 4317); if collector only accepts HTTP, set `OtlpExportProtocol.HttpProtobuf` |\n| `Meter` \u002F `ActivitySource` lifecycle | `ActivitySource` should be static; create `Meter` via `IMeterFactory` from DI (not `new Meter()`) for proper lifetime management and testability |\n","# Configuring OpenTelemetry in .NET\n\n## When to Use\n\n- Adding distributed tracing to an ASP.NET Core application\n- Setting up OpenTelemetry exporters (OTLP is the primary protocol; Jaeger accepts OTLP natively; Prometheus OTLP ingestion requires explicit opt-in)\n- Creating custom metrics or trace spans for business operations\n- Troubleshooting distributed trace context propagation across services\n\n## When Not to Use\n\n- The user wants application-level logging only (use ILogger, Serilog)\n- The user is using Application Insights SDK directly (different API)\n- The user needs APM with a commercial vendor's proprietary SDK\n\n## Inputs\n\n| Input | Required | Description |\n|-------|----------|-------------|\n| ASP.NET Core project | Yes | The application to instrument |\n| Observability backend | No | Where to export: OTLP collector, Aspire dashboard, Jaeger (accepts OTLP natively) |\n\n## Workflow\n\n### Step 1: Install the correct packages\n\n**There are many OpenTelemetry NuGet packages. Install exactly these:**\n\n```bash\n# Core SDK + ASP.NET Core instrumentation + logging integration\ndotnet add package OpenTelemetry.Extensions.Hosting\ndotnet add package OpenTelemetry.Instrumentation.AspNetCore\ndotnet add package OpenTelemetry.Instrumentation.Http\n\n# Exporter\ndotnet add package OpenTelemetry.Exporter.OpenTelemetryProtocol  # OTLP exporter for traces, metrics, AND logs\n\n# Optional — dev\u002Flocal debugging only (do NOT include in production deployments)\n# dotnet add package OpenTelemetry.Exporter.Console\n```\n\n**Do NOT install `OpenTelemetry` alone** — you need `OpenTelemetry.Extensions.Hosting` for proper DI integration.\n\n#### Optional: additional auto-instrumentation packages\n\nInstall only the packages that match the libraries your application uses:\n\n```bash\ndotnet add package OpenTelemetry.Instrumentation.SqlClient           # SQL Server queries\ndotnet add package OpenTelemetry.Instrumentation.EntityFrameworkCore  # EF Core\ndotnet add package OpenTelemetry.Instrumentation.GrpcNetClient       # gRPC calls\ndotnet add package OpenTelemetry.Instrumentation.Runtime             # GC, thread pool metrics\n```\n\n### Step 2: Configure all signals in Program.cs\n\n```csharp\nusing OpenTelemetry.Resources;\nusing OpenTelemetry.Trace;\nusing OpenTelemetry.Metrics;\nusing OpenTelemetry.Logs;\n\nvar builder = WebApplication.CreateBuilder(args);\n\nbuilder.Services.AddOpenTelemetry()\n    .ConfigureResource(resource => resource\n        .AddService(serviceName: builder.Environment.ApplicationName))\n    .WithTracing(tracing => tracing\n        .AddAspNetCoreInstrumentation(options =>\n        {\n            \u002F\u002F Filter out health check endpoints from traces\n            options.Filter = httpContext =>\n                !httpContext.Request.Path.StartsWithSegments(\"\u002Fhealthz\");\n        })\n        .AddHttpClientInstrumentation(options =>\n        {\n            options.RecordException = true;\n        })\n        \u002F\u002F Optional: add SQL instrumentation if using SqlClient directly\n        \u002F\u002F .AddSqlClientInstrumentation(options =>\n        \u002F\u002F {\n        \u002F\u002F     options.SetDbStatementForText = true;\n        \u002F\u002F     options.RecordException = true;\n        \u002F\u002F })\n        \u002F\u002F Custom activity sources (must match ActivitySource names in your code)\n        .AddSource(\"MyApp.Orders\")\n        .AddSource(\"MyApp.Payments\")\n        .AddSource(\"MyApp.Messaging\"))\n    .WithMetrics(metrics => metrics\n        .AddAspNetCoreInstrumentation()\n        .AddHttpClientInstrumentation()\n        \u002F\u002F Optional: .AddRuntimeInstrumentation() for GC and thread pool metrics\n        \u002F\u002F   (requires OpenTelemetry.Instrumentation.Runtime package)\n        \u002F\u002F Custom meters (must match Meter names in your code)\n        .AddMeter(\"MyApp.Metrics\"))\n    .WithLogging(logging =>\n    {\n        logging.IncludeScopes = true;\n        \u002F\u002F logging.IncludeFormattedMessage = true;  \u002F\u002F Enable if you need the formatted message string in log exports\n    })\n    \u002F\u002F Single OTLP exporter for all signals — reads OTEL_EXPORTER_OTLP_ENDPOINT\n    \u002F\u002F env var (defaults to http:\u002F\u002Flocalhost:4317). Override via environment variable\n    \u002F\u002F or appsettings.json configuration.\n    .UseOtlpExporter();\n```\n\n### Step 3: Understanding log–trace correlation\n\nThe `.WithLogging()` call in Step 2 integrates ILogger with OpenTelemetry:\n\n- Each log entry automatically includes TraceId and SpanId for correlation with traces\n- The service resource from `.ConfigureResource()` propagates to logs automatically\n- `UseOtlpExporter()` applies to logs alongside traces and metrics\n- No additional packages or separate `SetResourceBuilder` call needed\n\n### Step 4: Create custom spans (Activities) for business operations\n\n```csharp\nusing System.Diagnostics;\nusing Microsoft.Extensions.Logging;\n\npublic class OrderService\n{\n    \u002F\u002F Create an ActivitySource matching what you registered in Step 2\n    private static readonly ActivitySource ActivitySource = new(\"MyApp.Orders\");\n    private readonly ILogger\u003COrderService> _logger;\n\n    public OrderService(ILogger\u003COrderService> logger) => _logger = logger;\n\n    public async Task\u003COrder> ProcessOrderAsync(CreateOrderRequest request)\n    {\n        \u002F\u002F Start a new span\n        using var activity = ActivitySource.StartActivity(\"ProcessOrder\");\n\n        \u002F\u002F Add attributes (tags) to the span\n        activity?.SetTag(\"order.customer_id\", request.CustomerId);\n        activity?.SetTag(\"order.item_count\", request.Items.Count);\n\n        try\n        {\n            \u002F\u002F Child span for validation\n            using (var validationActivity = ActivitySource.StartActivity(\"ValidateOrder\"))\n            {\n                await ValidateOrderAsync(request);\n                validationActivity?.SetTag(\"validation.result\", \"passed\");\n            }\n\n            \u002F\u002F Child span for payment\n            using (var paymentActivity = ActivitySource.StartActivity(\"ProcessPayment\",\n                ActivityKind.Client))  \u002F\u002F Client = outgoing call\n            {\n                paymentActivity?.SetTag(\"payment.method\", request.PaymentMethod);\n                await ProcessPaymentAsync(request);\n            }\n\n            var order = new Order { Id = Guid.NewGuid(), CustomerId = request.CustomerId, Status = \"Completed\" };\n\n            activity?.SetTag(\"order.status\", \"completed\");\n            activity?.SetStatus(ActivityStatusCode.Ok);\n\n            return order;\n        }\n        catch (Exception ex)\n        {\n            activity?.SetStatus(ActivityStatusCode.Error, ex.Message);\n            \u002F\u002F Log via ILogger — OpenTelemetry captures this with trace correlation.\n            \u002F\u002F Prefer logging over activity.RecordException() as OTel is deprecating\n            \u002F\u002F span events for exception recording in favor of log-based exceptions.\n            _logger.LogError(ex, \"Order processing failed for customer {CustomerId}\", request.CustomerId);\n            throw;\n        }\n    }\n}\n```\n\n**Critical: `ActivitySource` name must match `AddSource(\"...\")` in configuration.** Unmatched sources are silently ignored — this is the #1 debugging issue.\n\n### Step 5: Create custom metrics\n\nUse `IMeterFactory` (injected via DI) to create meters — this ensures proper lifetime management and testability.\n\n```csharp\nusing System.Diagnostics;\nusing System.Diagnostics.Metrics;\n\npublic class OrderMetrics\n{\n    private readonly Counter\u003Clong> _ordersProcessed;\n    private readonly Histogram\u003Cdouble> _orderProcessingDuration;\n    private readonly UpDownCounter\u003Cint> _activeOrders;\n\n    public OrderMetrics(IMeterFactory meterFactory)\n    {\n        \u002F\u002F Meter name must match AddMeter(\"...\") in configuration\n        var meter = meterFactory.Create(\"MyApp.Metrics\");\n\n        \u002F\u002F Counter — use for things that only go up\n        _ordersProcessed = meter.CreateCounter\u003Clong>(\n            \"orders.processed\", \"orders\", \"Total orders successfully processed\");\n\n        \u002F\u002F Histogram — use for measuring distributions (latency, sizes)\n        _orderProcessingDuration = meter.CreateHistogram\u003Cdouble>(\n            \"orders.processing_duration\", \"ms\", \"Time to process an order\");\n\n        \u002F\u002F UpDownCounter — use for things that go up AND down\n        _activeOrders = meter.CreateUpDownCounter\u003Cint>(\n            \"orders.active\", \"orders\", \"Currently processing orders\");\n    }\n\n    public void RecordOrderProcessed(string region, double durationMs)\n    {\n        \u002F\u002F Tags enable dimensional filtering (by region, status, etc.)\n        var tags = new TagList\n        {\n            { \"region\", region },\n            { \"order.type\", \"standard\" }\n        };\n\n        _ordersProcessed.Add(1, tags);\n        _orderProcessingDuration.Record(durationMs, tags);\n    }\n}\n```\n\nRegister `OrderMetrics` in DI:\n\n```csharp\nbuilder.Services.AddSingleton\u003COrderMetrics>();\n```\n\n### Step 6: Configure context propagation for distributed scenarios\n\nTrace context propagation is automatic for HTTP calls when using `AddHttpClientInstrumentation()`. For non-HTTP scenarios:\n\n```csharp\nusing System;\nusing System.Collections.Generic;\nusing System.Diagnostics;\nusing OpenTelemetry.Context.Propagation;\n\n\u002F\u002F ActivitySource should be static — register via .AddSource(\"MyApp.Messaging\") in Step 2\nprivate static readonly ActivitySource MessageSource = new(\"MyApp.Messaging\");\n\n\u002F\u002F Manual context propagation (e.g., across message queues)\n\u002F\u002F On the SENDING side:\nvar propagator = Propagators.DefaultTextMapPropagator;\nvar activityContext = Activity.Current?.Context ?? default;\nvar context = new PropagationContext(activityContext, Baggage.Current);\nvar carrier = new Dictionary\u003Cstring, string>();\n\npropagator.Inject(context, carrier, (dict, key, value) => dict[key] = value);\n\u002F\u002F Send carrier dictionary as message headers\n\n\u002F\u002F On the RECEIVING side:\nvar parentContext = propagator.Extract(default, carrier,\n    (dict, key) => dict.TryGetValue(key, out var value) ? new[] { value } : Array.Empty\u003Cstring>());\n\nBaggage.Current = parentContext.Baggage;\nusing var activity = MessageSource.StartActivity(\"ProcessMessage\",\n    ActivityKind.Consumer,\n    parentContext.ActivityContext);  \u002F\u002F Links to parent trace!\n```\n\n## Validation\n\n- [ ] Traces appear in the observability backend (Jaeger, Aspire dashboard, etc.)\n- [ ] HTTP requests automatically create spans with correct verb, URL, status code\n- [ ] Custom `ActivitySource` names match `AddSource()` registrations\n- [ ] Custom `Meter` names match `AddMeter()` registrations\n- [ ] Logs include TraceId and SpanId for correlation\n- [ ] Health check endpoints are filtered from traces\n- [ ] Exception details appear on error spans\n\n## Common Pitfalls\n\n| Pitfall | Solution |\n|---------|----------|\n| `ActivitySource.StartActivity` returns null | Source name doesn't match any `AddSource()` — names must match exactly |\n| Traces not appearing in exporter | Check OTLP endpoint: gRPC uses port 4317, HTTP uses 4318 |\n| Missing HTTP client spans | Ensure `AddHttpClientInstrumentation()` is registered; it works for both `IHttpClientFactory`\u002FDI and `new HttpClient()` (use `IHttpClientFactory` for lifetime management) |\n| High cardinality tags | Don't use user IDs, request IDs, or UUIDs as metric tags — explodes storage |\n| OTLP gRPC vs HTTP mismatch | Default is gRPC (port 4317); if collector only accepts HTTP, set `OtlpExportProtocol.HttpProtobuf` |\n| `Meter` \u002F `ActivitySource` lifecycle | `ActivitySource` should be static; create `Meter` via `IMeterFactory` from DI (not `new Meter()`) for proper lifetime management and testability |\n",{"name":5,"risk":24,"source":25,"version":30,"category":31,"description":7,"disable-model-invocation":20},"low",{"path":26,"commit":27,"license":15,"repository":28,"imported_at":29},"plugins\u002Fdotnet-aspnetcore\u002Fskills\u002Fconfiguring-opentelemetry-dotnet\u002FSKILL.md","8f3b1a2c","microsoft\u002Fskills","2026-09-20","1.0.0","cloud","main","2d1750717747097b602acf30bd09a7cbd4b4c6ea","awesome_skills\u002Fcloud\u002Fconfiguring-opentelemetry-dotnet","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous","2026-11-09 11:45:36",{"source":8,"skillName":5,"commands":39,"prompt":49,"zipAvailable":50},[40,43,46],{"tool":41,"command":42},"npx","npx skills add Mr-Nobody-Anonymous\u002FAll-skills --skill configuring-opentelemetry-dotnet",{"tool":44,"command":45},"bunx","bunx skills add Mr-Nobody-Anonymous\u002FAll-skills --skill configuring-opentelemetry-dotnet",{"tool":47,"command":48},"pnpm","pnpm dlx skills add Mr-Nobody-Anonymous\u002FAll-skills --skill configuring-opentelemetry-dotnet","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fcloud\u002Fconfiguring-opentelemetry-dotnet\u002FSKILL.md",true,[],[53,61,68,75,82,89],{"skillNo":54,"name":55,"nameZh":6,"description":56,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":57,"categories":58,"keywords":59,"publishedAt":60},"01M7FFFZPC2025JQQHPHDX154J","dei-assessment","Assess diversity, equity, and inclusion with metrics. TRIGGERS - Use when user needs help with dei-assessment related tasks.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fdei-assessment\u002FSKILL.md",[],[],"2026-11-16 10:05:34",{"skillNo":62,"name":63,"nameZh":6,"description":64,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":65,"categories":66,"keywords":67,"publishedAt":60},"01M7FFFWN8H4WA7A6Y398QKB6J","dei-action-plan","Create DEI action plans with goals and initiatives. TRIGGERS - Use when user needs help with dei-action-plan related tasks.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fdei-action-plan\u002FSKILL.md",[],[],{"skillNo":69,"name":70,"nameZh":6,"description":71,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":72,"categories":73,"keywords":74,"publishedAt":60},"01M7FFFSHTM0QZRVZ2NRJTJ0PY","culture-fit-assessment","Design culture add assessment processes. TRIGGERS - Use when user needs help with culture-fit-assessment related tasks.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fculture-fit-assessment\u002FSKILL.md",[],[],{"skillNo":76,"name":77,"nameZh":6,"description":78,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":79,"categories":80,"keywords":81,"publishedAt":60},"01M7FFFMA12RKEQA38KHJSXXPS","cowork-to-code-bridge","Use an already-installed, independently verified cowork-to-code bridge to run narrowly approved actions on the user's own macOS, Linux, or WSL2 machine through a local file queue.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fcowork-to-code-bridge\u002FSKILL.md",[],[],{"skillNo":83,"name":84,"nameZh":6,"description":85,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":86,"categories":87,"keywords":88,"publishedAt":60},"01M7FFFH1F6M8YRGW5V487GH1K","counter-offer-response","Draft counter-offer responses for retention. TRIGGERS - Use when user needs help with counter-offer-response related tasks.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fcounter-offer-response\u002FSKILL.md",[],[],{"skillNo":90,"name":91,"nameZh":6,"description":92,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":93,"categories":94,"keywords":95,"publishedAt":60},"01M7FFFDGEHV8Y7J9N40HZXW52","continuous-feedback-system","Design continuous feedback systems. TRIGGERS - Use when user needs help with continuous-feedback-system related tasks.","https:\u002F\u002Fgithub.com\u002FMr-Nobody-Anonymous\u002FAll-skills\u002Fblob\u002Fmain\u002Fawesome_skills\u002Fhr-people\u002Fcontinuous-feedback-system\u002FSKILL.md",[],[]]