OpenTelemetry.Instrumentation.Http 1.18.0

Prefix Reserved
dotnet add package OpenTelemetry.Instrumentation.Http --version 1.18.0
                    
NuGet\Install-Package OpenTelemetry.Instrumentation.Http -Version 1.18.0
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="OpenTelemetry.Instrumentation.Http" Version="1.18.0" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="OpenTelemetry.Instrumentation.Http" Version="1.18.0" />
                    
Directory.Packages.props
<PackageReference Include="OpenTelemetry.Instrumentation.Http" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add OpenTelemetry.Instrumentation.Http --version 1.18.0
                    
#r "nuget: OpenTelemetry.Instrumentation.Http, 1.18.0"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package OpenTelemetry.Instrumentation.Http@1.18.0
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=OpenTelemetry.Instrumentation.Http&version=1.18.0
                    
Install as a Cake Addin
#tool nuget:?package=OpenTelemetry.Instrumentation.Http&version=1.18.0
                    
Install as a Cake Tool

HttpClient and HttpWebRequest instrumentation for OpenTelemetry

Status
Stability Stable
Code Owners @open-telemetry/dotnet-contrib-maintainers

NuGet NuGet codecov.io

This is an Instrumentation Library, which instruments System.Net.Http.HttpClient and System.Net.HttpWebRequest and collects metrics and traces about outgoing HTTP requests.

This component is based on the v1.23 of http semantic conventions. For details on the default set of attributes that are added, checkout Traces and Metrics sections below.

Steps to enable OpenTelemetry.Instrumentation.Http

Step 1: Install Package

Add a reference to the OpenTelemetry.Instrumentation.Http package. Also, add any other instrumentations & exporters you will need.

dotnet add package OpenTelemetry.Instrumentation.Http

Step 2: Enable HTTP Instrumentation at application startup

HTTP instrumentation must be enabled at application startup.

Traces

Starting with .NET 9, trace instrumentation is natively implemented, and the HttpClient library emits attributes defined in the OpenTelemetry Specification. When running on .NET 9+ this instrumentation library will not add/change/override any attributes set by the native instrumentation but it is still required for performing context propagation using the OpenTelemetry SDK and supports additional features not available in runtime (enrichment, filtering, etc.).

The following example demonstrates adding HttpClient instrumentation with the extension method .AddHttpClientInstrumentation() on TracerProviderBuilder to a console application. This example also sets up the OpenTelemetry Console Exporter, which requires adding the package OpenTelemetry.Exporter.Console to the application.

using OpenTelemetry;
using OpenTelemetry.Trace;

public class Program
{
    public static void Main(string[] args)
    {
        using var tracerProvider = Sdk.CreateTracerProviderBuilder()
            .AddHttpClientInstrumentation()
            .AddConsoleExporter()
            .Build();
    }
}

Following list of attributes are added by default on activity. See http-spans for more details about each individual attribute:

  • error.type
  • http.request.method
  • http.request.method_original
  • http.response.status_code
  • network.protocol.version
  • server.address
  • server.port
  • url.full - By default, the values in the query component of the url are replaced with the text Redacted. For example, ?key1=value1&key2=value2 becomes ?key1=Redacted&key2=Redacted. You can disable this redaction by setting the environment variable OTEL_DOTNET_EXPERIMENTAL_HTTPCLIENT_DISABLE_URL_QUERY_REDACTION to true.

Enrich Api can be used if any additional attributes are required on activity.

Metrics

The following example demonstrates adding HttpClient instrumentation with the extension method .AddHttpClientInstrumentation() on MeterProviderBuilder to a console application. This example also sets up the OpenTelemetry Console Exporter, which requires adding the package OpenTelemetry.Exporter.Console to the application.

using OpenTelemetry;
using OpenTelemetry.Metrics;

public class Program
{
    public static void Main(string[] args)
    {
        using var meterProvider = Sdk.CreateMeterProviderBuilder()
            .AddHttpClientInstrumentation()
            .AddConsoleExporter()
            .Build();
    }
}

Refer to this example to see how to enable this instrumentation in an ASP.NET Core application.

Refer to this example to see how to enable this instrumentation in an ASP.NET application.

Following list of attributes are added by default on http.client.request.duration metric. See http-metrics for more details about each individual attribute. .NET 8 and above supports additional metrics, see list of metrics produced for more details.

  • error.type
  • http.request.method
  • http.response.status_code
  • network.protocol.version
  • server.address
  • server.port
  • url.scheme
Enriching HttpClient metrics

Metrics enrichment allows adding custom tags to the http.client.request.duration metric. This is useful for adding low-cardinality categorization to dashboards or alerts.

Starting from .NET 8, use HttpMetricsEnrichmentContext to add custom tags to the built-in HttpClient metrics. Enrichment is registered per request by calling HttpMetricsEnrichmentContext.AddCallback. A common way to register the callback in one place is to use a custom DelegatingHandler that runs before the request is sent to the server. The callback can use the request, response, or exception information available on the HttpMetricsEnrichmentContext instance.

using System.Net.Http;
using System.Net.Http.Metrics;

using HttpClient client = new(
    new EnrichmentHandler { InnerHandler = new HttpClientHandler() });

await client.GetStringAsync("https://example.com");

sealed class EnrichmentHandler : DelegatingHandler
{
    protected override Task<HttpResponseMessage> SendAsync(
        HttpRequestMessage request,
        CancellationToken cancellationToken)
    {
        HttpMetricsEnrichmentContext.AddCallback(request, static context =>
        {
            var requestKind = context.Request.Method == HttpMethod.Get
                ? "read"
                : "write";

            context.AddCustomTag("request.kind", requestKind);
        });

        return base.SendAsync(request, cancellationToken);
    }
}

When using IHttpClientFactory, register the handler with AddHttpMessageHandler.

using Microsoft.Extensions.DependencyInjection;
using System.Net.Http;
using System.Net.Http.Metrics;

ServiceCollection services = new();
services.AddHttpClient("enriched")
    .AddHttpMessageHandler(() => new EnrichmentHandler());

using ServiceProvider serviceProvider = services.BuildServiceProvider();
HttpClient client = serviceProvider
    .GetRequiredService<IHttpClientFactory>()
    .CreateClient("enriched");

await client.GetStringAsync("https://example.com");

The enrichment callback is invoked only when the http.client.request.duration instrument is enabled by metrics collection, for example through AddHttpClientInstrumentation(), AddMeter(), or another metrics listener.

List of metrics produced

When the application targets NETFRAMEWORK, .NET6.0 or .NET7.0, the instrumentation emits the following metric:

Name Details
http.client.request.duration Specification

Starting from .NET 8, metrics instrumentation is natively implemented, and the HttpClient library has incorporated support for built-in metrics following the OpenTelemetry semantic conventions. The library includes additional metrics beyond those defined in the specification, covering additional scenarios for HttpClient users. When the application targets .NET 8 and newer versions, the instrumentation library automatically enables all built-in metrics by default.

Note that the AddHttpClientInstrumentation() extension simplifies the process of enabling all built-in metrics via a single line of code. Alternatively, for more granular control over emitted metrics, you can utilize the AddMeter() extension on MeterProviderBuilder for meters listed in built-in-metrics-system-net. Using AddMeter() for metrics activation eliminates the need to take dependency on the instrumentation library package and calling AddHttpClientInstrumentation().

If you utilize AddHttpClientInstrumentation() and wish to exclude unnecessary metrics, you can utilize Views to achieve this.

There is no difference in features or emitted metrics when enabling metrics using AddMeter() or AddHttpClientInstrumentation() on .NET 8 and newer versions.

The http.client.request.duration metric is emitted in seconds as per the semantic convention. While the convention recommends using custom histogram buckets , this feature is not yet available via .NET Metrics API. A workaround has been included in OTel SDK starting version 1.6.0 which applies recommended buckets by default for http.client.request.duration. This applies to all targeted frameworks.

Advanced configuration

Tracing

This instrumentation can be configured to change the default behavior by using HttpClientTraceInstrumentationOptions. It is important to note that there are differences between .NET Framework and newer .NET/.NET Core runtimes which govern what options are used. On .NET Framework, HttpClient uses the HttpWebRequest API. On .NET & .NET Core, HttpWebRequest uses the HttpClient API. As such, depending on the runtime, only one half of the "filter" & "enrich" options are used.

.NET & .NET Core
Filter HttpClient API

This instrumentation by default collects all the outgoing HTTP requests. It allows filtering of requests by using the FilterHttpRequestMessage function option. This defines the condition for allowable requests. The filter function receives the request object (HttpRequestMessage) representing the outgoing request and does not collect telemetry about the request if the filter function returns false or throws an exception.

The following code snippet shows how to use FilterHttpRequestMessage to only allow GET requests.

using var tracerProvider = Sdk.CreateTracerProviderBuilder()
    .AddHttpClientInstrumentation(
        // Note: Only called on .NET & .NET Core runtimes.
        (options) => options.FilterHttpRequestMessage =
            (httpRequestMessage) =>
            {
                // Example: Only collect telemetry about HTTP GET requests.
                return httpRequestMessage.Method.Equals(HttpMethod.Get);
            })
    .AddConsoleExporter()
    .Build();

It is important to note that this