Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add HttpClient metrics for .NET Framework #4768

Closed
Closed
Show file tree
Hide file tree
Changes from 6 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ OpenTelemetry.Instrumentation.Http.HttpClientInstrumentationOptions.RecordExcept
OpenTelemetry.Metrics.MeterProviderBuilderExtensions
OpenTelemetry.Trace.TracerProviderBuilderExtensions
static OpenTelemetry.Metrics.MeterProviderBuilderExtensions.AddHttpClientInstrumentation(this OpenTelemetry.Metrics.MeterProviderBuilder builder) -> OpenTelemetry.Metrics.MeterProviderBuilder
static OpenTelemetry.Metrics.MeterProviderBuilderExtensions.AddHttpClientInstrumentation(this OpenTelemetry.Metrics.MeterProviderBuilder builder, string name) -> OpenTelemetry.Metrics.MeterProviderBuilder
static OpenTelemetry.Trace.TracerProviderBuilderExtensions.AddHttpClientInstrumentation(this OpenTelemetry.Trace.TracerProviderBuilder builder) -> OpenTelemetry.Trace.TracerProviderBuilder
static OpenTelemetry.Trace.TracerProviderBuilderExtensions.AddHttpClientInstrumentation(this OpenTelemetry.Trace.TracerProviderBuilder builder, string name, System.Action<OpenTelemetry.Instrumentation.Http.HttpClientInstrumentationOptions> configureHttpClientInstrumentationOptions) -> OpenTelemetry.Trace.TracerProviderBuilder
static OpenTelemetry.Trace.TracerProviderBuilderExtensions.AddHttpClientInstrumentation(this OpenTelemetry.Trace.TracerProviderBuilder builder, System.Action<OpenTelemetry.Instrumentation.Http.HttpClientInstrumentationOptions> configureHttpClientInstrumentationOptions) -> OpenTelemetry.Trace.TracerProviderBuilder
2 changes: 2 additions & 0 deletions src/OpenTelemetry.Instrumentation.Http/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

## Unreleased

* Added support for exposing `http.client.duration` on .NET Framework for `HttpWebRequest`, including `HttpClient`. Metrics support requires tracing to be enabled via `AddHttpClientInstrumentation` (#4768)[https://github.com/open-telemetry/opentelemetry-dotnet/pull/4768]

## 1.5.1-beta.1

Released 2023-Jul-20
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
#if NETFRAMEWORK
using System.Collections;
using System.Diagnostics;
using System.Diagnostics.Metrics;
using System.Net;
using System.Reflection;
using System.Reflection.Emit;
Expand All @@ -39,13 +40,17 @@ internal static class HttpWebRequestActivitySource
internal static readonly AssemblyName AssemblyName = typeof(HttpWebRequestActivitySource).Assembly.GetName();
internal static readonly string ActivitySourceName = AssemblyName.Name + ".HttpWebRequest";
internal static readonly string ActivityName = ActivitySourceName + ".HttpRequestOut";
internal static readonly string InstrumentationName = AssemblyName.Name;

internal static readonly Func<HttpWebRequest, string, IEnumerable<string>> HttpWebRequestHeaderValuesGetter = (request, name) => request.Headers.GetValues(name);
internal static readonly Action<HttpWebRequest, string, string> HttpWebRequestHeaderValuesSetter = (request, name, value) => request.Headers.Add(name, value);

private static readonly Version Version = AssemblyName.Version;
private static readonly ActivitySource WebRequestActivitySource = new ActivitySource(ActivitySourceName, Version.ToString());

private static readonly Meter WebRequestMeter = new Meter(InstrumentationName, Version.ToString());
private static readonly Histogram<double> HttpClientDuration;

private static HttpClientInstrumentationOptions options;

private static bool emitOldAttributes;
Expand Down Expand Up @@ -87,6 +92,7 @@ static HttpWebRequestActivitySource()
PerformInjection();

Options = new HttpClientInstrumentationOptions();
HttpClientDuration = WebRequestMeter.CreateHistogram<double>("http.client.duration", "ms", "Measures the duration of outbound HTTP requests.");
}
catch (Exception ex)
{
Expand Down Expand Up @@ -396,6 +402,47 @@ private static void ProcessResult(IAsyncResult asyncResult, AsyncCallback asyncC
}

activity.Stop();

TagList tags = default;

// see the spec https://github.com/open-telemetry/opentelemetry-specification/blob/v1.20.0/specification/trace/semantic_conventions/http.md
if (emitOldAttributes)
{
foreach (var tag in activity.TagObjects)
matt-hensley marked this conversation as resolved.
Show resolved Hide resolved
matt-hensley marked this conversation as resolved.
Show resolved Hide resolved
matt-hensley marked this conversation as resolved.
Show resolved Hide resolved
{
switch (tag.Key)
{
case SemanticConventions.AttributeHttpMethod:
case SemanticConventions.AttributeHttpScheme:
case SemanticConventions.AttributeHttpFlavor:
case SemanticConventions.AttributeNetPeerName:
case SemanticConventions.AttributeNetPeerPort:
case SemanticConventions.AttributeHttpStatusCode:
tags.Add(new KeyValuePair<string, object>(tag.Key, tag.Value));
break;
}
}
}

// see the spec https://github.com/open-telemetry/semantic-conventions/blob/v1.21.0/docs/http/http-spans.md
if (emitNewAttributes)
{
foreach (var tag in activity.TagObjects)
matt-hensley marked this conversation as resolved.
Show resolved Hide resolved
{
switch (tag.Key)
{
case SemanticConventions.AttributeHttpRequestMethod:
case SemanticConventions.AttributeNetworkProtocolVersion:
case SemanticConventions.AttributeServerAddress:
case SemanticConventions.AttributeServerPort:
case SemanticConventions.AttributeHttpResponseStatusCode:
tags.Add(new KeyValuePair<string, object>(tag.Key, tag.Value));
break;
}
}
}

HttpClientDuration.Record(activity.Duration.TotalMilliseconds, tags);
}

private static void PrepareReflectionObjects()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,12 +34,26 @@ public static class MeterProviderBuilderExtensions
/// <returns>The instance of <see cref="MeterProviderBuilder"/> to chain the calls.</returns>
public static MeterProviderBuilder AddHttpClientInstrumentation(
this MeterProviderBuilder builder)
{
return AddHttpClientInstrumentation(builder, name: null);
}

/// <summary>
/// Enables HttpClient instrumentation.
/// </summary>
/// <param name="builder"><see cref="MeterProviderBuilder"/> being configured.</param>
/// <param name="name">Name which is used when retrieving options.</param>
/// <returns>The instance of <see cref="MeterProviderBuilder"/> to chain the calls.</returns>
public static MeterProviderBuilder AddHttpClientInstrumentation(
matt-hensley marked this conversation as resolved.
Show resolved Hide resolved
this MeterProviderBuilder builder, string name)
{
Guard.ThrowIfNull(builder);

// Note: Warm-up the status code mapping.
_ = TelemetryHelper.BoxedStatusCodes;

name ??= Options.DefaultName;

builder.ConfigureServices(services =>
{
services.RegisterOptionsFactory(configuration => new HttpClientMetricInstrumentationOptions(configuration));
Expand All @@ -54,7 +68,22 @@ public static MeterProviderBuilder AddHttpClientInstrumentation(
// RecordException - probably doesn't make sense for metric instrumentation

builder.AddMeter(HttpClientMetrics.InstrumentationName);
matt-hensley marked this conversation as resolved.
Show resolved Hide resolved
return builder.AddInstrumentation(sp => new HttpClientMetrics(
builder.AddInstrumentation(sp => new HttpClientMetrics(
sp.GetRequiredService<IOptionsMonitor<HttpClientMetricInstrumentationOptions>>().CurrentValue));

#if NETFRAMEWORK
builder.AddMeter(HttpWebRequestActivitySource.InstrumentationName);
builder.ConfigureServices(s =>
{
s.ConfigureOpenTelemetryMeterProvider((sp, _) =>
{
var options = sp.GetRequiredService<IOptionsMonitor<HttpClientInstrumentationOptions>>().Get(name);

HttpWebRequestActivitySource.Options = options;
});
});
#endif

return builder;
}
}
2 changes: 1 addition & 1 deletion src/OpenTelemetry.Instrumentation.Http/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ public class Program
#### Metrics

> **Note**
> Metrics are not available for .NET Framework.
> Metrics are only available for .NET Framework when tracing is enabled.
matt-hensley marked this conversation as resolved.
Show resolved Hide resolved

The following example demonstrates adding `HttpClient` instrumentation with the
extension method `.AddHttpClientInstrumentation()` on `MeterProviderBuilder` to
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -159,9 +159,6 @@ public async Task HttpOutCallsAreCollectedSuccessfullyAsync(HttpTestData.HttpOut
Assert.True(enrichWithExceptionCalled);
}

#if NETFRAMEWORK
Assert.Empty(requestMetrics);
#else
Assert.Single(requestMetrics);

var metric = requestMetrics[0];
Expand Down Expand Up @@ -193,7 +190,11 @@ public async Task HttpOutCallsAreCollectedSuccessfullyAsync(HttpTestData.HttpOut
var method = new KeyValuePair<string, object>(SemanticConventions.AttributeHttpMethod, tc.Method);
var scheme = new KeyValuePair<string, object>(SemanticConventions.AttributeHttpScheme, "http");
var statusCode = new KeyValuePair<string, object>(SemanticConventions.AttributeHttpStatusCode, tc.ResponseCode == 0 ? 200 : tc.ResponseCode);
#if NETFRAMEWORK
var flavor = new KeyValuePair<string, object>(SemanticConventions.AttributeHttpFlavor, "1.1");
#else
var flavor = new KeyValuePair<string, object>(SemanticConventions.AttributeHttpFlavor, "2.0");
#endif
var hostName = new KeyValuePair<string, object>(SemanticConventions.AttributeNetPeerName, tc.ResponseExpected ? host : "sdlfaldfjalkdfjlkajdflkajlsdjf");
var portNumber = new KeyValuePair<string, object>(SemanticConventions.AttributeNetPeerPort, port);
Assert.Contains(hostName, attributes);
Expand All @@ -211,7 +212,6 @@ public async Task HttpOutCallsAreCollectedSuccessfullyAsync(HttpTestData.HttpOut
Assert.DoesNotContain(statusCode, attributes);
Assert.Equal(5, attributes.Length);
}
#endif
}

[Fact]
Expand Down