This explanation covers monitoring and logging setup for the application using the OpenTelemetry .NET SDK. The OpenTelemetry project provides a single set of APIs, libraries, agents, and instrumentation that work together to generate and collect telemetry data (metrics, logs, and traces) from your application.
Options for Monitoring and Logging
- Automatic Instrumentation
Automatic instrumentation is available for .NET applications and services. It sends traces and metrics without requiring code changes. To enable automatic instrumentation, set the following environment variables to true before launching your application:
- OTEL_DOTNET_AUTO_LOGS_CONSOLE_EXPORTER_ENABLED
- OTEL_DOTNET_AUTO_METRICS_CONSOLE_EXPORTER_ENABLED
- OTEL_DOTNET_AUTO_TRACES_CONSOLE_EXPORTER_ENABLED
For more information, see the documentation on OpenTelemetry .NET SDK Auto-instrumentation.
- Manual Instrumentation
For manual instrumentation, modify the Program.cs
file to include the necessary namespaces and setup code. Install the required packages:
dotnet add package OpenTelemetry
dotnet add package OpenTelemetry.Exporter.Console --version 1.5.1
Here’s an example of a Program.cs
file with manual instrumentation:
using OpenTelemetry.Metrics;
using OpenTelemetry.Resources;
using OpenTelemetry.Trace;
var meterProvider = Sdk.CreateMeterProvider();
using var tracerProvider = Sdk.CreateTracerProvider(
b => b
.AddSource("MyCompany.MyProject.MyService")
.SetResourceBuilder(ResourceBuilder.CreateDefault().AddService("my-service"))
.AddConsoleExporter());
For more information, see the documentation on manual instrumentation for OpenTelemetry .NET.
- Exporters
To visualize and analyze your telemetry, you will need to export your data to an OpenTelemetry Collector or a backend such as Jaeger, Zipkin, Prometheus, or a vendor-specific one. OpenTelemetry .NET provides many exporters, including OpenTelemetry Protocol (OTLP) exporters.
To configure an OTLP exporter, install the required package:
dotnet add package OpenTelemetry.Exporter.OpenTelemetryProtocol --version 1.5.1
Then, add the OTLP exporter after each call to AddConsoleExporter
.
For more information, see the documentation on OpenTelemetry .NET Exporters.
Dependencies and Technologies
- OpenTelemetry
- .NET
- NuGet
- GitHub Actions
- OpenTelemetry Protocol
- Prometheus
- Zipkin
- gRPC
- System.Net.Http.HttpClient and System.Net.HttpWebRequest
- Microsoft.Data.SqlClient and System.Data.SqlClient
For more information, see the documentation on OpenTelemetry .NET, OpenTelemetry .NET Contrib, OpenTelemetry .NET Automatic Instrumentation, and OpenTelemetry Instrumentation Libraries.