### Example: Separate Source Registration and Exporter Setup Source: https://github.com/open-telemetry/opentelemetry-dotnet/blob/main/docs/builders/configure-opentelemetry-provider.md Demonstrates registering instrumentation sources early and configuring exporters separately using `ConfigureOpenTelemetryTracerProvider` and `ConfigureOpenTelemetryMeterProvider`. ```csharp var builder = WebApplication.CreateBuilder(args); // Register sources (could be in a different file or method) builder.Services.ConfigureOpenTelemetryTracerProvider(tracing => tracing.AddSource("MyApp")); builder.Services.ConfigureOpenTelemetryMeterProvider(metrics => metrics.AddMeter("MyApp")); // Configure exporters and create the provider builder.Services.AddOpenTelemetry() .ConfigureResource(r => r.AddService("my-app")) .WithTracing(tracing => tracing.AddOtlpExporter()) .WithMetrics(metrics => metrics.AddOtlpExporter()); var app = builder.Build(); app.Run(); ``` -------------------------------- ### Run example using Docker Compose Source: https://github.com/open-telemetry/opentelemetry-dotnet/blob/main/examples/MicroserviceExample/README.md Start the application and all required dependencies including the OpenTelemetry Collector, Zipkin, and RabbitMQ. ```shell docker compose up --build ``` -------------------------------- ### Run Routing Logs Example Source: https://github.com/open-telemetry/opentelemetry-dotnet/blob/main/docs/logs/routing/README.md Navigate to the example directory and execute the application to observe log routing. ```sh cd docs/logs/routing dotnet run ``` -------------------------------- ### Full Multi-Signal OpenTelemetrySdk Initialization Source: https://github.com/open-telemetry/opentelemetry-dotnet/blob/main/docs/builders/opentelemetry-sdk-create.md A comprehensive example demonstrating the initialization of OpenTelemetrySdk with tracing, metrics, and logging, all configured to use OTLP exporters. This setup is suitable for applications requiring robust telemetry across all three signals. ```csharp using System.Diagnostics; using System.Diagnostics.Metrics; using Microsoft.Extensions.Logging; using OpenTelemetry; using OpenTelemetry.Logs; using OpenTelemetry.Metrics; using OpenTelemetry.Trace; var activitySource = new ActivitySource("MyApp"); var meter = new Meter("MyApp"); var requestCounter = meter.CreateCounter("requests"); using var sdk = OpenTelemetrySdk.Create(builder => builder .ConfigureResource(r => r.AddService("my-console-app")) .WithTracing(tracing => tracing .AddSource("MyApp") .AddOtlpExporter()) .WithMetrics(metrics => metrics .AddMeter("MyApp") .AddOtlpExporter()) .WithLogging(logging => logging .AddOtlpExporter())); var logger = sdk.GetLoggerFactory().CreateLogger(); using (var activity = activitySource.StartActivity("ProcessRequest")) { requestCounter.Add(1); logger.LogInformation("Request processed"); } // sdk.Dispose() flushes and shuts down all three providers. ``` -------------------------------- ### Install OpenTelemetry.Extensions.Hosting Source: https://github.com/open-telemetry/opentelemetry-dotnet/blob/main/src/OpenTelemetry.Extensions.Hosting/README.md Use the dotnet CLI to add the package to your project. ```shell dotnet add package OpenTelemetry.Extensions.Hosting ``` -------------------------------- ### Install DiagnosticSource package Source: https://github.com/open-telemetry/opentelemetry-dotnet/blob/main/src/OpenTelemetry.Api/README.md Install the required NuGet package for .NET instrumentation. ```shell dotnet add package System.Diagnostics.DiagnosticSource ``` -------------------------------- ### Install Prometheus HTTP Listener Package Source: https://github.com/open-telemetry/opentelemetry-dotnet/blob/main/src/OpenTelemetry.Exporter.Prometheus.HttpListener/README.md Installs the Prometheus HTTP Listener exporter package using the .NET CLI. ```shell dotnet add package --prerelease OpenTelemetry.Exporter.Prometheus.HttpListener ``` -------------------------------- ### Start Activity with Activity Links Source: https://github.com/open-telemetry/opentelemetry-dotnet/blob/main/src/OpenTelemetry.Api/README.md Include ActivityLinks to represent OpenTelemetry Links between spans. Providing links during creation is recommended for sampler consideration. This example requires OpenTelemetry .NET SDK 9.0.0 or later. ```csharp var activityLinks = new List(); var linkedContext1 = new ActivityContext( ActivityTraceId.CreateFromString("0af7651916cd43dd8448eb211c80319c"), ActivitySpanId.CreateFromString("b7ad6b7169203331"), ActivityTraceFlags.None); var linkedContext2 = new ActivityContext( ActivityTraceId.CreateFromString("4bf92f3577b34da6a3ce929d0e0e4736"), ActivitySpanId.CreateFromString("00f067aa0ba902b7"), ActivityTraceFlags.Recorded); activityLinks.Add(new ActivityLink(linkedContext1)); activityLinks.Add(new ActivityLink(linkedContext2)); var activity = activitySource.StartActivity( "ActivityWithLinks", ActivityKind.Server, default(ActivityContext), initialTags); ``` -------------------------------- ### Configure Multi-Signal OpenTelemetry Source: https://github.com/open-telemetry/opentelemetry-dotnet/blob/main/docs/builders/add-opentelemetry.md Full configuration example including tracing, metrics, and logging with OTLP exporters. ```csharp using OpenTelemetry.Logs; using OpenTelemetry.Metrics; using OpenTelemetry.Trace; var builder = WebApplication.CreateBuilder(args); // Clear default log providers if you want OTel to be the sole log sink builder.Logging.ClearProviders(); builder.Services.AddOpenTelemetry() .ConfigureResource(r => r .AddService( serviceName: "my-web-api", serviceVersion: "1.0.0")) .WithTracing(tracing => tracing .AddAspNetCoreInstrumentation() .AddHttpClientInstrumentation() .AddSource("MyApp") .AddOtlpExporter()) .WithMetrics(metrics => metrics .AddAspNetCoreInstrumentation() .AddHttpClientInstrumentation() .AddMeter("MyApp") .AddOtlpExporter()) .WithLogging(logging => logging .AddOtlpExporter()); var app = builder.Build(); app.MapGet("/", () => "Hello World"); app.Run(); ``` -------------------------------- ### Run Web API and Worker Service projects Source: https://github.com/open-telemetry/opentelemetry-dotnet/blob/main/examples/MicroserviceExample/README.md Execute the individual components of the example application from the project directory. ```shell dotnet run --project WebApi dotnet run --project WorkerService ``` -------------------------------- ### Create and Configure ASP.NET Core Project Source: https://github.com/open-telemetry/opentelemetry-dotnet/blob/main/docs/trace/getting-started-aspnetcore/README.md Commands to initialize a new web project and install the required OpenTelemetry instrumentation and exporter packages. ```sh dotnet new web -o aspnetcoreapp cd aspnetcoreapp ``` ```sh dotnet add package OpenTelemetry.Exporter.Console dotnet add package OpenTelemetry.Extensions.Hosting dotnet add package OpenTelemetry.Instrumentation.AspNetCore ``` -------------------------------- ### Install OpenTelemetry Propagators package Source: https://github.com/open-telemetry/opentelemetry-dotnet/blob/main/src/OpenTelemetry.Extensions.Propagators/README.md Add the required NuGet package to your .NET project. ```shell dotnet add package OpenTelemetry.Extensions.Propagators ``` -------------------------------- ### Install OTLP Exporter Package Source: https://github.com/open-telemetry/opentelemetry-dotnet/blob/main/src/OpenTelemetry.Exporter.OpenTelemetryProtocol/README.md Use the dotnet CLI to add the OpenTelemetry.Exporter.OpenTelemetryProtocol package to your project. ```shell dotnet add package OpenTelemetry.Exporter.OpenTelemetryProtocol ``` -------------------------------- ### Build a Basic MeterProvider Source: https://github.com/open-telemetry/opentelemetry-dotnet/blob/main/docs/metrics/customizing-the-sdk/README.md This snippet demonstrates how to create a basic MeterProvider with default configuration using Sdk.CreateMeterProviderBuilder().Build(). It's a starting point for further customization. ```csharp using OpenTelemetry; using OpenTelemetry.Metrics; using var meterProvider = Sdk.CreateMeterProviderBuilder().Build(); ``` -------------------------------- ### Install Prometheus Exporter Package Source: https://github.com/open-telemetry/opentelemetry-dotnet/blob/main/src/OpenTelemetry.Exporter.Prometheus.AspNetCore/README.md Use the dotnet CLI to add the OpenTelemetry.Exporter.Prometheus.AspNetCore package to your project. This command installs the pre-release version. ```shell dotnet add package --prerelease OpenTelemetry.Exporter.Prometheus.AspNetCore ``` -------------------------------- ### Install OpenTelemetry API package Source: https://github.com/open-telemetry/opentelemetry-dotnet/blob/main/src/OpenTelemetry.Api/README.md Use the .NET CLI to add the OpenTelemetry.Api package to your project. ```shell dotnet add package OpenTelemetry.Api ``` -------------------------------- ### Stress Test Example Output Source: https://github.com/open-telemetry/opentelemetry-dotnet/blob/main/test/OpenTelemetry.Tests.Stress/README.md Shows an example of the output observed while the stress test is running, including options, status, and performance metrics. ```text Options: {"Concurrency":20,"PrometheusInternalMetricsPort":9464,"DurationSeconds":0} Run OpenTelemetry.Tests.Stress.exe --help to see available options. Running (concurrency = 20, internalPrometheusEndpoint = http://localhost:9464/metrics/), press to stop, press to toggle statistics in the console... Loops: 17,384,826,748, Loops/Second: 2,375,222,037, CPU Cycles/Loop: 24, RunningTime (Seconds): 7 ``` -------------------------------- ### Start Activity with Initial Tags Source: https://github.com/open-telemetry/opentelemetry-dotnet/blob/main/src/OpenTelemetry.Api/README.md Provide an initial set of tags (attributes) during activity creation. This is recommended as samplers can only consider information present at creation time. Requires importing System.Collections.Generic. ```csharp var initialTags = new ActivityTagsCollection(); initialTags["com.mycompany.product.mytag1"] = "tagValue1"; initialTags["com.mycompany.product.mytag2"] = "tagValue2"; var activity = activitySource.StartActivity( "ActivityName", ActivityKind.Server, "00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01", initialTags); ``` -------------------------------- ### Start and Tag an Activity Source: https://github.com/open-telemetry/opentelemetry-dotnet/blob/main/docs/trace/getting-started-console/README.md Initiate an Activity, set tags (attributes), and define its status. Ensure the ActivitySource is correctly named. ```csharp using (var activity = MyActivitySource.StartActivity("SayHello")) { activity?.SetTag("foo", 1); activity?.SetTag("bar", "Hello, World!"); activity?.SetTag("baz", new int[] { 1, 2, 3 }); activity?.SetStatus(ActivityStatusCode.Ok); } ``` -------------------------------- ### Configure OpenTelemetry in Worker Service Source: https://github.com/open-telemetry/opentelemetry-dotnet/blob/main/docs/builders/add-opentelemetry.md Setup for background services using Host.CreateApplicationBuilder. ```csharp using OpenTelemetry.Trace; var builder = Host.CreateApplicationBuilder(args); builder.Services.AddOpenTelemetry() .ConfigureResource(r => r.AddService("my-worker")) .WithTracing(tracing => tracing .AddSource("MyWorker") .AddOtlpExporter()); builder.Services.AddHostedService(); var host = builder.Build(); host.Run(); ``` -------------------------------- ### Starting a Custom Span as a Root Span Source: https://github.com/open-telemetry/opentelemetry-dotnet/blob/main/docs/trace/customizing-the-sdk/README.md Shows how to explicitly start a custom span as a root span by providing a default parent context. This bypasses the parent-based sampling decision, ensuring the custom span is not dropped due to an unsampled parent. ```csharp using var activity = activitySource.StartActivity("Hello", ActivityKind.Internal, parentContext: default); ``` -------------------------------- ### Install Telemetry Abstractions Package Source: https://github.com/open-telemetry/opentelemetry-dotnet/blob/main/docs/logs/complex-objects/README.md Command to add the required NuGet package for complex object logging. ```sh dotnet add package Microsoft.Extensions.Telemetry.Abstractions ``` -------------------------------- ### Install OpenTelemetry Packages Source: https://github.com/open-telemetry/opentelemetry-dotnet/blob/main/docs/logs/getting-started-aspnetcore/README.md Commands to add the necessary OpenTelemetry NuGet packages for console exporting and hosting integration. ```sh dotnet add package OpenTelemetry.Exporter.Console dotnet add package OpenTelemetry.Extensions.Hosting ``` -------------------------------- ### Start an Activity Source: https://github.com/open-telemetry/opentelemetry-dotnet/blob/main/src/OpenTelemetry.Api/README.md Create an activity instance to represent an operation. Always check for null as the activity may not be created if no listeners are active. ```csharp var activity = activitySource.StartActivity("ActivityName"); ``` -------------------------------- ### Install OpenTelemetry Packages Source: https://github.com/open-telemetry/opentelemetry-dotnet/blob/main/docs/metrics/getting-started-aspnetcore/README.md Add necessary OpenTelemetry packages for console exporting and ASP.NET Core instrumentation to your project. ```sh dotnet add package OpenTelemetry.Exporter.Console dotnet add package OpenTelemetry.Extensions.Hosting dotnet add package OpenTelemetry.Instrumentation.AspNetCore ``` -------------------------------- ### Example Trace Output Source: https://github.com/open-telemetry/opentelemetry-dotnet/blob/main/docs/trace/getting-started-aspnetcore/README.md Sample console output showing the structure of an OpenTelemetry trace generated by the application. ```text Activity.TraceId: c28f7b480d5c7dfc30cfbd80ad29028d Activity.SpanId: 27e478bbf9fdec10 Activity.TraceFlags: Recorded Activity.ActivitySourceName: Microsoft.AspNetCore Activity.DisplayName: GET / Activity.Kind: Server Activity.StartTime: 2024-07-04T13:03:37.3318740Z Activity.Duration: 00:00:00.3693734 Activity.Tags: server.address: localhost server.port: 5154 http.request.method: GET url.scheme: https url.path: / network.protocol.version: 2 user_agent.original: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0.0.0 Safari/537.36 http.route: / http.response.status_code: 200 Resource associated with Activity: service.name: getting-started-aspnetcore service.instance.id: a388466b-4969-4bb0-ad96-8f39527fa66b telemetry.sdk.name: opentelemetry telemetry.sdk.language: dotnet telemetry.sdk.version: 1.9.0 ``` -------------------------------- ### Install Zipkin Exporter Package Source: https://github.com/open-telemetry/opentelemetry-dotnet/blob/main/src/OpenTelemetry.Exporter.Zipkin/README.md Use the dotnet CLI to add the Zipkin exporter package to your project. ```shell dotnet add package OpenTelemetry.Exporter.Zipkin ``` -------------------------------- ### Configure OpenTelemetry in ASP.NET Core Source: https://github.com/open-telemetry/opentelemetry-dotnet/blob/main/docs/builders/add-opentelemetry.md Minimal setup for tracing in a web application using the Generic Host builder. ```csharp using OpenTelemetry.Trace; var builder = WebApplication.CreateBuilder(args); builder.Services.AddOpenTelemetry() .ConfigureResource(r => r.AddService("my-web-api")) .WithTracing(tracing => tracing .AddAspNetCoreInstrumentation() .AddConsoleExporter()); var app = builder.Build(); app.MapGet("/", () => "Hello World"); app.Run(); ``` -------------------------------- ### Run Prometheus with Exemplar Storage and OTLP Receiver Source: https://github.com/open-telemetry/opentelemetry-dotnet/blob/main/docs/metrics/exemplars/README.md Starts the Prometheus server with feature flags for exemplar storage and OTLP receiver enabled. This allows Prometheus to store and receive exemplar data. ```sh ./prometheus --enable-feature=exemplar-storage --web.enable-otlp-receiver ``` -------------------------------- ### Log Output Example Source: https://github.com/open-telemetry/opentelemetry-dotnet/blob/main/docs/logs/complex-objects/README.md Expected console output showing the structured attributes of the logged object. ```text LogRecord.Timestamp: 2024-01-12T19:01:16.0604084Z LogRecord.CategoryName: Program LogRecord.Severity: Fatal LogRecord.SeverityText: Critical LogRecord.FormattedMessage: LogRecord.Body: LogRecord.Attributes (Key:Value): CompanyName: Contoso Fresh Vegetables, Inc. RecallReasonDescription: due to a possible health risk from Listeria monocytogenes ProductType: Food & Beverages ProductDescription: Salads BrandName: Contoso LogRecord.EventId: 252550133 LogRecord.EventName: FoodRecallNotice ``` -------------------------------- ### Configure Metrics with OTLP Exporter Source: https://github.com/open-telemetry/opentelemetry-dotnet/blob/main/src/OpenTelemetry.Exporter.OpenTelemetryProtocol/README.md When using UseOtlpExporter, you can further configure metrics by adding specific meters or instrumentation. This example shows how to listen to custom telemetry and use ASP.NET Core instrumentation. ```csharp appBuilder.Services.AddOpenTelemetry() .UseOtlpExporter() .WithMetrics(metrics => metrics .AddMeter(MyMeter.Name) // Listen to custom telemetry .AddAspNetCoreInstrumentation() // Use instrumentation to listen to telemetry ); ``` -------------------------------- ### Start and Tag Activity Source: https://github.com/open-telemetry/opentelemetry-dotnet/blob/main/docs/trace/README.md Check Activity.IsAllDataRequested before setting tags for performance. Use a using statement for automatic disposal. Set attributes using Activity.SetTag. ```csharp using (var activity = MyActivitySource.StartActivity("SayHello")) { if (activity != null && activity.IsAllDataRequested == true) { activity.SetTag("http.url", "http://www.mywebsite.com"); } } ``` -------------------------------- ### OpenTelemetrySdk Initialization with Logging Source: https://github.com/open-telemetry/opentelemetry-dotnet/blob/main/docs/builders/opentelemetry-sdk-create.md Initialize OpenTelemetrySdk to include logging capabilities alongside tracing and metrics. This example demonstrates how to add a console exporter for logs and retrieve an ILoggerFactory to create loggers. ```csharp using Microsoft.Extensions.Logging; using OpenTelemetry; using OpenTelemetry.Logs; using var sdk = OpenTelemetrySdk.Create(builder => builder .WithLogging(logging => logging.AddConsoleExporter())); var logger = sdk.GetLoggerFactory().CreateLogger(); logger.LogInformation("Hello from {Source}", "OpenTelemetry"); ``` -------------------------------- ### Setup TracerProvider in Console App Source: https://github.com/open-telemetry/opentelemetry-dotnet/blob/main/docs/trace/README.md For simpler applications like Console apps, manually create and manage the `TracerProvider` instance. Ensure it is disposed of properly at application shutdown to avoid dropping activities. ```csharp using var tracerProvider = Sdk.CreateTracerProviderBuilder() .AddSource("MyActivitySource") .AddOtlpExporter() .Build(); // Application logic here // TracerProvider is disposed automatically at the end of the scope. ``` -------------------------------- ### Prometheus Metrics Example Source: https://github.com/open-telemetry/opentelemetry-dotnet/blob/main/test/OpenTelemetry.Tests.Stress/README.md Illustrates a section of the metrics exposed by the stress test in Prometheus format, including loop counts, rates, and CPU cycles. ```text # HELP OpenTelemetry_Tests_Stress_Loops The total number of `Run()` invocations that are completed. # TYPE OpenTelemetry_Tests_Stress_Loops counter OpenTelemetry_Tests_Stress_Loops 1844902947 1658950184752 # HELP OpenTelemetry_Tests_Stress_LoopsPerSecond The rate of `Run()` invocations based on a small sliding window of few hundreds of milliseconds. # TYPE OpenTelemetry_Tests_Stress_LoopsPerSecond gauge OpenTelemetry_Tests_Stress_LoopsPerSecond 9007731.132075472 1658950184752 # HELP OpenTelemetry_Tests_Stress_CpuCyclesPerLoop The average CPU cycles for each `Run()` invocation, based on a small sliding window of few hundreds of milliseconds. # TYPE OpenTelemetry_Tests_Stress_CpuCyclesPerLoop gauge OpenTelemetry_Tests_Stress_CpuCyclesPerLoop 3008 1658950184752 # HELP process_runtime_dotnet_gc_collections_count Number of garbage collections that have occurred since process start. .NET objects are allocated from this heap. Object allocations from unmanaged languages such as C/C++ do not use this heap. # TYPE process_runtime_dotnet_gc_collections_count counter process_runtime_dotnet_gc_collections_count{generation="gen2"} 0 1658950184752 process_runtime_dotnet_gc_collections_count{generation="gen1"} 0 1658950184752 process_runtime_dotnet_gc_collections_count{generation="gen0"} 0 1658950184752 # HELP process_runtime_dotnet_gc_allocations_size_bytes Count of bytes allocated on the managed GC heap since the process start. .NET objects are allocated from this heap. Object allocations from unmanaged languages such as C/C++ do not use this heap. # TYPE process_runtime_dotnet_gc_allocations_size_bytes counter process_runtime_dotnet_gc_allocations_size_bytes 5485192 1658950184752 ``` -------------------------------- ### Start Activity with Parent Context from Traceparent String Source: https://github.com/open-telemetry/opentelemetry-dotnet/blob/main/src/OpenTelemetry.Api/README.md Provide the parent context as a single string formatted according to the W3C Trace-Context 'traceparent' header. This simplifies integration with systems that only provide the traceparent header. ```csharp var activity = activitySource.StartActivity( "ActivityName", ActivityKind.Server, "00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01"); ``` -------------------------------- ### Configure Tracing with OTLP Exporter Source: https://github.com/open-telemetry/opentelemetry-dotnet/blob/main/src/OpenTelemetry.Exporter.OpenTelemetryProtocol/README.md Similar to metrics, tracing can be configured with UseOtlpExporter by adding specific activity sources or instrumentation. This example demonstrates adding custom trace sources and ASP.NET Core instrumentation. ```csharp appBuilder.Services.AddOpenTelemetry() .UseOtlpExporter() .WithTracing(tracing => tracing .AddSource(MyActivitySource.Name) // Listen to custom telemetry .AddAspNetCoreInstrumentation() // Use instrumentation to listen to telemetry ); ``` -------------------------------- ### Initialize ASP.NET Core Project Source: https://github.com/open-telemetry/opentelemetry-dotnet/blob/main/docs/logs/getting-started-aspnetcore/README.md Commands to create a new web application directory and initialize the project. ```sh dotnet new web -o aspnetcoreapp cd aspnetcoreapp ``` -------------------------------- ### Custom Span Creation in ASP.NET Core App Source: https://github.com/open-telemetry/opentelemetry-dotnet/blob/main/docs/trace/customizing-the-sdk/README.md Demonstrates how to create a custom ActivitySource and start a custom span within an ASP.NET Core application. This setup can lead to custom spans being dropped if the parent ASP.NET Core activity is not sampled. ```csharp var activitySource = new ActivitySource("MyCompany.MyProduct"); builder.Services.AddOpenTelemetry() .WithTracing(tracing => tracing .AddSource("MyCompany.MyProduct") .AddConsoleExporter()); app.MapGet("/hello", () => { using var activity = activitySource.StartActivity("Hello"); return "Hello, World!"; }); ``` -------------------------------- ### Define a custom processor with dependency injection Source: https://github.com/open-telemetry/opentelemetry-dotnet/blob/main/docs/trace/customizing-the-sdk/README.md Example of a custom processor that requires a custom service dependency. This is a prerequisite for the DI examples. ```csharp public class MyCustomProcessor : BaseProcessor { public MyCustomProcessor(MyCustomService myCustomService) { // Implementation not important } } ``` -------------------------------- ### Initialize and run a .NET console application Source: https://github.com/open-telemetry/opentelemetry-dotnet/blob/main/docs/metrics/getting-started-prometheus-grafana/README.md Commands to create a new console project and execute it. ```sh dotnet new console --output getting-started-prometheus-grafana cd getting-started-prometheus-grafana dotnet run ``` -------------------------------- ### Unformatted Log Message Example Source: https://github.com/open-telemetry/opentelemetry-dotnet/blob/main/src/OpenTelemetry/README.md Example of a log message when FormatMessage is set to false. Placeholders and raw parameter values are shown. ```txt 2025-07-24T01:45:04.1020880Z:Measurements from Instrument '{0}', Meter '{1}' will be ignored. Reason: '{2}'. Suggested action: '{3}'{dotnet.gc.collections}{System.Runtime}{Instrument belongs to a Meter not subscribed by the provider.}{Use AddMeter to add the Meter to the provider.} ``` -------------------------------- ### Console Metrics Output Example Source: https://github.com/open-telemetry/opentelemetry-dotnet/blob/main/docs/metrics/getting-started-aspnetcore/README.md Example of metrics output from the console exporter, showing HTTP request duration and status codes. ```text Metric Name: http.server.request.duration, Description: Duration of HTTP server requests., Unit: s, Metric Type: Histogram Instrumentation scope (Meter): Name: Microsoft.AspNetCore.Hosting (2026-04-02T22:41:03.8661885Z, 2026-04-02T22:41:12.0061720Z] http.request.method: GET http.response.status_code: 200 http.route: / network.protocol.version: 1.1 url.scheme: http Value: Sum: 0.0276842 Count: 1 Min: 0.0276842 Max: 0.0276842 (-Infinity,0.005]:0 (0.005,0.01]:0 (0.01,0.025]:0 (0.025,0.05]:1 (0.05,0.075]:0 (0.075,0.1]:0 (0.1,0.25]:0 (0.25,0.5]:0 (0.5,0.75]:0 (0.75,1]:0 (1,2.5]:0 (2.5,5]:0 (5,7.5]:0 (7.5,10]:0 (10,+Infinity]:0 ``` -------------------------------- ### Minimal OpenTelemetrySdk Initialization Source: https://github.com/open-telemetry/opentelemetry-dotnet/blob/main/docs/builders/opentelemetry-sdk-create.md Use this minimal example to set up OpenTelemetry with tracing and metrics in a console application. It configures a service resource and adds console exporters for both signals. The SDK is disposed automatically via the 'using' statement. ```csharp using OpenTelemetry; using var sdk = OpenTelemetrySdk.Create(builder => builder .ConfigureResource(r => r.AddService("my-console-app")) .WithTracing(tracing => tracing .AddSource("MyApp") .AddConsoleExporter()) .WithMetrics(metrics => metrics .AddMeter("MyApp") .AddConsoleExporter())); // Application logic goes here. // sdk.Dispose() is called by `using`, which flushes all signals. ``` -------------------------------- ### Create and Run Console Application Source: https://github.com/open-telemetry/opentelemetry-dotnet/blob/main/docs/metrics/exemplars/README.md This snippet shows the commands to create a new console application, navigate to its directory, and run it. ```sh dotnet new console --output exemplars cd exemplars dotnet run ``` -------------------------------- ### Formatted Log Message Example Source: https://github.com/open-telemetry/opentelemetry-dotnet/blob/main/src/OpenTelemetry/README.md Example of a log message when FormatMessage is set to true. Placeholders are replaced with actual parameter values for readability. ```txt 2025-07-24T01:44:44.7059260Z:Measurements from Instrument 'dotnet.gc.collections', Meter 'System.Runtime' will be ignored. Reason: 'Instrument belongs to a Meter not subscribed by the provider.'. Suggested action: 'Use AddMeter to add the Meter to the provider.' ``` -------------------------------- ### Create and Run Console Application Source: https://github.com/open-telemetry/opentelemetry-dotnet/blob/main/docs/trace/getting-started-jaeger/README.md Use these commands to create a new console application and run it. This sets up the basic project structure. ```sh dotnet new console --output getting-started-jaeger cd getting-started-jaeger dotnet run ``` -------------------------------- ### Start Activity with Specific ActivityKind Source: https://github.com/open-telemetry/opentelemetry-dotnet/blob/main/src/OpenTelemetry.Api/README.md Use this overload to explicitly set the ActivityKind (e.g., Server, Client, Producer, Consumer, Internal) when starting an activity. The default is Internal. ```csharp var activity = activitySource.StartActivity("ActivityName", ActivityKind.Server); ``` -------------------------------- ### Console Trace Output Example Source: https://github.com/open-telemetry/opentelemetry-dotnet/blob/main/docs/trace/getting-started-jaeger/README.md This is an example of trace output that appears in the console when the application is run with the Console Exporter configured. It shows details like TraceId, SpanId, and associated tags. ```text > dotnet run Activity.TraceId: 693f1d15634bfe6ba3254d6f9d20df27 Activity.SpanId: 429cc5a90a753fb3 Activity.TraceFlags: Recorded Activity.ParentSpanId: 0d64498b736c9a11 Activity.ActivitySourceName: System.Net.Http Activity.DisplayName: GET Activity.Kind: Client Activity.StartTime: 2024-07-04T13:18:12.2408786Z Activity.Duration: 00:00:02.1028562 Activity.Tags: http.request.method: GET server.address: httpstat.us server.port: 443 url.full: https://httpstat.us/200?sleep=Redacted network.protocol.version: 1.1 http.response.status_code: 200 Resource associated with Activity: service.name: DemoApp service.version: 1.0.0 service.instance.id: 03ccafab-e9a7-440a-a9cd-9a0163e0d06c telemetry.sdk.name: opentelemetry telemetry.sdk.language: dotnet telemetry.sdk.version: 1.9.0 ... ``` -------------------------------- ### Create and Run a .NET Console Application Source: https://github.com/open-telemetry/opentelemetry-dotnet/blob/main/docs/logs/getting-started-console/README.md Use the .NET CLI to create a new console application, navigate to its directory, and run it. ```sh dotnet new console --output getting-started cd getting-started dotnet run ``` -------------------------------- ### Register custom services and processors with Sdk.CreateTracerProviderBuilder() Source: https://github.com/open-telemetry/opentelemetry-dotnet/blob/main/docs/trace/customizing-the-sdk/README.md Demonstrates registering a custom service and processor using `ConfigureServices` and `AddProcessor` when `Sdk.CreateTracerProviderBuilder()` is used. The `TracerProvider` manages its own `IServiceCollection` in this scenario. ```csharp using var tracerProvider = Sdk.CreateTracerProviderBuilder() .ConfigureServices(services => { services.AddSingleton(); }) .AddProcessor() .Build(); ``` -------------------------------- ### Create a new console application Source: https://github.com/open-telemetry/opentelemetry-dotnet/blob/main/docs/metrics/getting-started-console/README.md Use the .NET CLI to create a new console application and navigate to its directory. ```sh dotnet new console --output getting-started cd getting-started ``` -------------------------------- ### Increment counter in a loop Source: https://github.com/open-telemetry/opentelemetry-dotnet/blob/main/docs/metrics/getting-started-prometheus-grafana/README.md Example loop to continuously increment a counter until a key is pressed. ```csharp Console.WriteLine("Press any key to exit"); while (!Console.KeyAvailable) { MyFruitCounter.Add(1, new("name", "apple"), new("color", "red")); MyFruitCounter.Add(2, new("name", "lemon"), new("color", "yellow")); ... Thread.Sleep(300); } ``` -------------------------------- ### Configure MeterProvider with Console Exporter Source: https://github.com/open-telemetry/opentelemetry-dotnet/blob/main/docs/metrics/getting-started-console/README.md Set up the MeterProvider to collect metrics from a specific meter and export them to the console. ```csharp var meterProvider = Sdk.CreateMeterProviderBuilder() .AddMeter("MyCompany.MyProduct.MyLibrary") .AddConsoleExporter() .Build(); ``` -------------------------------- ### Configure Multi-Signal Telemetry Source: https://github.com/open-telemetry/opentelemetry-dotnet/blob/main/docs/builders/sdk-create-tracer-provider-builder.md Demonstrates setting up independent providers for tracing, metrics, and logging using legacy builder patterns. ```csharp using System.Diagnostics; using System.Diagnostics.Metrics; using Microsoft.Extensions.Logging; using OpenTelemetry; using OpenTelemetry.Logs; using OpenTelemetry.Metrics; using OpenTelemetry.Trace; // Tracing using var tracerProvider = Sdk.CreateTracerProviderBuilder() .AddSource("MyApp") .AddConsoleExporter() .Build(); // Metrics using var meterProvider = Sdk.CreateMeterProviderBuilder() .AddMeter("MyApp") .AddConsoleExporter() .Build(); // Logging (uses ILoggerFactory, not a provider builder) using var loggerFactory = LoggerFactory.Create(builder => builder .AddOpenTelemetry(options => options.AddConsoleExporter())); var logger = loggerFactory.CreateLogger(); logger.LogInformation("Application started"); ``` -------------------------------- ### Define Complex Data Type Source: https://github.com/open-telemetry/opentelemetry-dotnet/blob/main/docs/logs/complex-objects/README.md Example struct representing a complex object to be logged. ```csharp public struct FoodRecallNotice { public string? BrandName { get; set; } public string? ProductDescription { get; set; } public string? ProductType { get; set; } public string? RecallReasonDescription { get; set; } public string? CompanyName { get; set; } } ``` -------------------------------- ### Clone the opentelemetry-dotnet repository Source: https://github.com/open-telemetry/opentelemetry-dotnet/blob/main/CONTRIBUTING.md Clone the main repository to your local machine to start contributing. ```sh git clone https://github.com/open-telemetry/opentelemetry-dotnet.git ``` -------------------------------- ### Configure Meter Provider (Immediate Execution) Source: https://github.com/open-telemetry/opentelemetry-dotnet/blob/main/docs/builders/configure-opentelemetry-provider.md Configures the meter provider immediately. Safe for registering services like meters or instruments. ```csharp public static IServiceCollection ConfigureOpenTelemetryMeterProvider( this IServiceCollection services, Action configure); ``` -------------------------------- ### Build OpenTelemetry.slnx Source: https://github.com/open-telemetry/opentelemetry-dotnet/blob/main/AGENTS.md Builds the entire OpenTelemetry solution in Release configuration. ```sh dotnet build OpenTelemetry.slnx --configuration Release ``` -------------------------------- ### View Log Output Source: https://github.com/open-telemetry/opentelemetry-dotnet/blob/main/docs/logs/getting-started-aspnetcore/README.md Example of the structured log output generated by the OpenTelemetry Console Exporter. ```text LogRecord.Timestamp: 2023-09-06T22:59:17.9787564Z LogRecord.CategoryName: getting-started-aspnetcore LogRecord.Severity: Info LogRecord.SeverityText: Information LogRecord.Body: Starting the app... LogRecord.Attributes (Key:Value): OriginalFormat (a.k.a Body): Starting the app... LogRecord.EventId: 225744744 LogRecord.EventName: StartingApp ... LogRecord.Timestamp: 2023-09-06T22:59:18.0644378Z LogRecord.CategoryName: Microsoft.Hosting.Lifetime LogRecord.Severity: Info LogRecord.SeverityText: Information LogRecord.Body: Now listening on: {address} LogRecord.Attributes (Key:Value): address: http://localhost:5000 OriginalFormat (a.k.a Body): Now listening on: {address} LogRecord.EventId: 14 LogRecord.EventName: ListeningOnAddress ... LogRecord.Timestamp: 2023-09-06T23:00:46.1639248Z LogRecord.TraceId: 3507087d60ae4b1d2f10e68f4e40784a LogRecord.SpanId: c51be9f19c598b69 LogRecord.TraceFlags: None LogRecord.CategoryName: Program LogRecord.Severity: Info LogRecord.SeverityText: Information LogRecord.Body: Food `{name}` price changed to `{price}`. LogRecord.Attributes (Key:Value): name: artichoke price: 9.99 OriginalFormat (a.k.a Body): Food `{name}` price changed to `{price}`. LogRecord.EventId: 344095174 LogRecord.EventName: FoodPriceChanged ... ``` -------------------------------- ### Setup TracerProvider in ASP.NET Core App Source: https://github.com/open-telemetry/opentelemetry-dotnet/blob/main/docs/trace/README.md For ASP.NET Core applications, use `AddOpenTelemetry` and `WithTraces` methods from the `OpenTelemetry.Extensions.Hosting` package to correctly set up the `TracerProvider`. This ensures the provider is managed correctly throughout the application's lifecycle. ```csharp builder.Services.AddOpenTelemetry() .WithTracing(tracingBuilder => tracingBuilder .AddAspNetCoreInstrumentation() .AddOtlpExporter()); ``` -------------------------------- ### View Stress Test Help Source: https://github.com/open-telemetry/opentelemetry-dotnet/blob/main/test/OpenTelemetry.Tests.Stress.Logs/README.md Displays available command-line arguments and configuration options for the stress test. ```sh dotnet run --framework net10.0 --configuration Release -- --help ``` -------------------------------- ### Inject Logger in Endpoint Source: https://github.com/open-telemetry/opentelemetry-dotnet/blob/main/docs/logs/getting-started-aspnetcore/README.md Example of using ILogger within an ASP.NET Core minimal API endpoint. ```csharp app.MapGet("/", (ILogger logger) => { logger.FoodPriceChanged("artichoke", 9.99); return "Hello from OpenTelemetry Logs!"; }); ``` -------------------------------- ### Run Prometheus with OTLP receiver Source: https://github.com/open-telemetry/opentelemetry-dotnet/blob/main/docs/metrics/getting-started-prometheus-grafana/README.md Command to start the Prometheus server with the OTLP receiver feature flag enabled. ```sh ./prometheus --web.enable-otlp-receiver ``` -------------------------------- ### Create a Counter instrument Source: https://github.com/open-telemetry/opentelemetry-dotnet/blob/main/docs/metrics/getting-started-console/README.md Instantiate a Counter instrument from a Meter to record numerical measurements. ```csharp private static readonly Counter MyFruitCounter = MyMeter.CreateCounter("MyFruitCounter"); ``` -------------------------------- ### Lint Markdown files Source: https://github.com/open-telemetry/opentelemetry-dotnet/blob/main/AGENTS.md Checks Markdown files for style and formatting issues using `markdownlint-cli`. Requires `markdownlint-cli` to be installed. ```sh markdownlint . ```