Integrating Open Telemetry Logging and Tracing in .NET Core Application
Add required packages for Open Telemetry Logging and Tracing
dotnet add package OpenTelemetry
dotnet add package OpenTelemetry.AutoInstrumentation
dotnet add package OpenTelemetry.Exporter.OpenTelemetryProtocol
dotnet add package OpenTelemetry.Extensions.Hosting
dotnet add package OpenTelemetry.Instrumentation.AspNetCore
dotnet add package OpenTelemetry.Instrumentation.Runtime
# This package is only required if you are using serilog.
dotnet add package Serilog.Sinks.OpenTelemetry
nuget packages for open telemetry
In appsettings.json, add section for OpenTelemetry Provider endpoint,
"OpenTelemetry": {
"Endpoint": "YOUR_TELEMETRY_ENDPOINT",
},
Logging (with Serilog)
In Program.cs, integrate the OpenTelemetry with Serilog using the OpenTelemetry sink.
// Retrieve the OpenTelemetry endpoint from configuration
var openTelemetryEndpoint = configuration["OpenTelemetry:Endpoint"];
// Configure Serilog to log to a file
var loggerConfig = new LoggerConfiguration();
// If the config exists, add it to the Logger Configuration.
if (!string.IsNullOrEmpty(openTelemetryEndpoint))
{
loggerConfig = loggerConfig.WriteTo.OpenTelemetry(options =>
{
options.Endpoint = openTelemetryEndpoint;
});
}
//Initialize Logger
Log.Logger = loggerConfig.CreateLogger();
Logging (w/o Serilog)
If you want to implement logging without Serilog, you can directly add the section below and skip the section in the Program.cs file.
var openTelemetryEndpoint = configuration["OpenTelemetry:Endpoint"];
services.AddOpenTelemetry()
.ConfigureResource(resource => resource.AddService(serviceName: "YOUR_APP_NAME"))
.WithLogging(logging =>
{
logging.AddOtlpExporter(otlpOptions =>
{
otlpOptions.Endpoint = new Uri(openTelemetryEndpoint);
otlpOptions.Protocol = OtlpExportProtocol.Grpc;
});
})
Tracing
To implement the tracing, we will add the following sections in Service Configuration.
services.AddOpenTelemetry()
.ConfigureResource(resource => resource.AddService(serviceName: "YOUR_APP_NAME"))
.WithTracing(tracing => tracing
.AddAspNetCoreInstrumentation()
//.AddHttpClientInstrumentation()
.AddEntityFrameworkCoreInstrumentation()
.AddSqlClientInstrumentation()
.AddOtlpExporter(otlpOptions =>
{
//SigNoz Endpoint
otlpOptions.Endpoint = new Uri(openTelemetryEndpoint);
otlpOptions.Protocol = OtlpExportProtocol.Grpc;
}));