Observability is vital for maintaining high-performance distributed systems. When diagnosing bottlenecks, tracking database queries alongside your HTTP request lifecycle provides end-to-end visibility into where latency occurs.

OpenTelemetry provides a vendor-neutral standard for collecting and exporting telemetry data. Integrating OpenTelemetry with Entity Framework Core (EF Core) allows you to automatically track database command durations, parameters, and execution traces.

Implementing OpenTelemetry EF Core Instrumentation

Step 1: Install Required NuGet Packages

Add the OpenTelemetry hosting, EF Core instrumentation, and console exporter packages to your .NET project:

Bash

dotnet add package OpenTelemetry.Extensions.Hosting
dotnet add package OpenTelemetry.Instrumentation.EntityFrameworkCore
dotnet add package OpenTelemetry.Exporter.Console

Verification: Check your project file (.csproj) to confirm that OpenTelemetry.Instrumentation.EntityFrameworkCore and the related packages are correctly listed as package references.

Step 2: Configure OpenTelemetry Tracing in Program.cs

Register OpenTelemetry in your dependency injection container and enable Entity Framework Core instrumentation during application startup:

C#

using OpenTelemetry.Trace;

var builder = WebApplication.CreateBuilder(args);

// Register OpenTelemetry tracing services
builder.Services.AddOpenTelemetry()
    .WithTracing(tracing => tracing
        .AddAspNetCoreInstrumentation()
        .AddEntityFrameworkCoreInstrumentation(options =>
        {
            // Set to true to include the generated SQL statement text in the trace attributes
            options.SetDbStatementForText = true;
        })
        .AddConsoleExporter()); // Exports telemetry traces directly to the console for verification

var app = builder.Build();

// Configure your middleware pipeline and endpoints...
app.Run();

Verification: Run dotnet build to ensure your solution compiles cleanly without missing namespace references.

Step 3: Verify Trace Collection

Start your application and trigger an API endpoint that executes a database query.

Verification: Inspect your application console output to confirm that OpenTelemetry trace spans containing the executed SQL commands and execution durations are successfully captured and logged.