[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7D0383R4QETSWTHSPNCHEB1":3,"skill-same:01M7D0383R4QETSWTHSPNCHEB1":44},{"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":24,"commitSha":25,"skillDirectory":26,"forksCount":14,"repositoryHtmlUrl":27,"repositoryHomepageUrl":6,"ownerHtmlUrl":28,"ownerBlogUrl":6,"ownerDescription":6,"updatedAt":29,"install":30,"resources":43},"01M7D0383R4QETSWTHSPNCHEB1","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.","itsmejay18\u002FAI-Skills-for-My-Development-Stack","itsmejay18","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F167779943?v=4","01M7CZRFC6DDZA5V2CX8WDSZED","Jay Jemino Ababon ","01M7CZRFCVRNW1SFHSQXEJ3CQN",0,"MIT","https:\u002F\u002Fgithub.com\u002Fitsmejay18\u002FAI-Skills-for-My-Development-Stack\u002Fblob\u002Fmain\u002F02-CSharp-WPF-Desktop-Development\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.\nlicense: MIT\n---\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,"license":15,"description":7},"main","30954af1dcd1a74b63f05deb2e2c41e5ecae4a82","02-CSharp-WPF-Desktop-Development\u002Fconfiguring-opentelemetry-dotnet","https:\u002F\u002Fgithub.com\u002Fitsmejay18\u002FAI-Skills-for-My-Development-Stack","https:\u002F\u002Fgithub.com\u002Fitsmejay18","2026-09-18 16:06:36",{"source":8,"skillName":5,"commands":31,"prompt":41,"zipAvailable":42},[32,35,38],{"tool":33,"command":34},"npx","npx skills add itsmejay18\u002FAI-Skills-for-My-Development-Stack --skill configuring-opentelemetry-dotnet",{"tool":36,"command":37},"bunx","bunx skills add itsmejay18\u002FAI-Skills-for-My-Development-Stack --skill configuring-opentelemetry-dotnet",{"tool":39,"command":40},"pnpm","pnpm dlx skills add itsmejay18\u002FAI-Skills-for-My-Development-Stack --skill configuring-opentelemetry-dotnet","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fitsmejay18\u002FAI-Skills-for-My-Development-Stack\u002Fblob\u002Fmain\u002F02-CSharp-WPF-Desktop-Development\u002Fconfiguring-opentelemetry-dotnet\u002FSKILL.md",true,[],[45,52,59,66,73,80],{"skillNo":46,"name":47,"nameZh":6,"description":48,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":49,"categories":50,"keywords":51,"publishedAt":19},"01M7D2RKBHPZ3E1RNN5DWHT550","vectorization","Design, implement, optimize, and review SIMD code in .NET. USE FOR: vectorizing scalar loops with TensorPrimitives, Vector64\u002F128\u002F256\u002F512, or platform hardware intrinsics; reviewing existing SIMD code, including Vector\u003CT>, for contract equivalence, tail handling, memory safety, portability, fallbacks, and measured performance. DO NOT USE FOR: performance work unrelated to SIMD or vectorization.","https:\u002F\u002Fgithub.com\u002Fitsmejay18\u002FAI-Skills-for-My-Development-Stack\u002Fblob\u002Fmain\u002F20-Performance-Optimization\u002Fvectorization\u002FSKILL.md",[],[],{"skillNo":53,"name":54,"nameZh":6,"description":55,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":56,"categories":57,"keywords":58,"publishedAt":19},"01M7D2RDJ7RN3QK8GJR0QTER1D","resolve-project-references","Guide for interpreting ResolveProjectReferences time in MSBuild performance summaries. Activate when ResolveProjectReferences appears as the most expensive target and developers are trying to optimize it directly. Explains that the reported time includes wait time for dependent project builds and is misleading. Guides users to focus on task self-time instead. Do not activate for general build performance -- use build-perf-diagnostics instead.","https:\u002F\u002Fgithub.com\u002Fitsmejay18\u002FAI-Skills-for-My-Development-Stack\u002Fblob\u002Fmain\u002F20-Performance-Optimization\u002Fresolve-project-references\u002FSKILL.md",[],[],{"skillNo":60,"name":61,"nameZh":6,"description":62,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":63,"categories":64,"keywords":65,"publishedAt":19},"01M7D2R1H2GTNZYHG9YRX3JDQW","optimizing-ef-core-queries","Optimize and improve the performance of slow Entity Framework Core (EF Core) queries: make them generate less SQL, make fewer database round-trips, and return results faster. Use whenever an EF Core or DbContext query or data-access path is slow or should be made faster — whether or not EF Core owns the database schema. For EF Core, not Dapper or raw ADO.NET.","https:\u002F\u002Fgithub.com\u002Fitsmejay18\u002FAI-Skills-for-My-Development-Stack\u002Fblob\u002Fmain\u002F20-Performance-Optimization\u002Foptimizing-ef-core-queries\u002FSKILL.md",[],[],{"skillNo":67,"name":68,"nameZh":6,"description":69,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":70,"categories":71,"keywords":72,"publishedAt":19},"01M7D2QREG04W1YT0NEBHEW5C9","microbenchmarking","Activate this skill when BenchmarkDotNet (BDN) is involved in the task — creating, running, configuring, or reviewing BDN benchmarks. Also activate when microbenchmarking .NET code would be useful and BenchmarkDotNet is the likely tool. Consider activating when answering a .NET performance question requires measurement and BenchmarkDotNet may be needed. Covers microbenchmark design, BDN configuration and project setup, how to run BDN microbenchmarks efficiently and effectively, and using BDN for side-by-side performance comparisons. Do NOT use for profiling\u002Ftracing .NET code (dotnet-trace, PerfView), production telemetry, or load\u002Fstress testing (Crank, k6).","https:\u002F\u002Fgithub.com\u002Fitsmejay18\u002FAI-Skills-for-My-Development-Stack\u002Fblob\u002Fmain\u002F20-Performance-Optimization\u002Fmicrobenchmarking\u002FSKILL.md",[],[],{"skillNo":74,"name":75,"nameZh":6,"description":76,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":77,"categories":78,"keywords":79,"publishedAt":19},"01M7D2QGE175XWPZVACVH2868Z","incremental-build","Guide for optimizing MSBuild incremental builds. USE FOR: builds slower than expected on subsequent runs, 'nothing changed but it rebuilds anyway', diagnosing why targets re-execute unnecessarily, fixing broken no-op builds. Covers 8 common causes: missing Inputs\u002FOutputs on custom targets, volatile properties in output paths (timestamps\u002FGUIDs), file writes outside tracked Outputs, missing FileWrites registration, glob changes, Visual Studio Fast Up-to-Date Check (FUTDC) issues. Key diagnostic: look for 'Building target completely' vs 'Skipping target' in binlog. DO NOT USE FOR: first-time build slowness (use build-perf-baseline), parallelism issues (use build-parallelism), evaluation-phase slowness (use eval-performance), non-MSBuild build systems.","https:\u002F\u002Fgithub.com\u002Fitsmejay18\u002FAI-Skills-for-My-Development-Stack\u002Fblob\u002Fmain\u002F20-Performance-Optimization\u002Fincremental-build\u002FSKILL.md",[],[],{"skillNo":81,"name":82,"nameZh":6,"description":83,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":84,"categories":85,"keywords":86,"publishedAt":19},"01M7D2Q1DQTC6K49R73WQTTPSB","eval-performance","Guide for diagnosing and improving MSBuild project evaluation performance. USE FOR: builds slow before any compilation starts, high evaluation time in binlog analysis, expensive glob patterns walking large directories (node_modules, .git, bin\u002Fobj), deep import chains (>20 levels), preprocessed output >10K lines indicating heavy evaluation, property functions with file I\u002FO ($([System.IO.File]::ReadAllText(...))), multiple evaluations per project. Covers the 5 MSBuild evaluation phases, glob optimization via DefaultItemExcludes, import chain analysis with \u002Fpp preprocessing. DO NOT USE FOR: compilation-time slowness (use build-perf-diagnostics), incremental build issues (use incremental-build), non-MSBuild build systems.","https:\u002F\u002Fgithub.com\u002Fitsmejay18\u002FAI-Skills-for-My-Development-Stack\u002Fblob\u002Fmain\u002F20-Performance-Optimization\u002Feval-performance\u002FSKILL.md",[],[]]