Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
19 commits
Select commit Hold shift + click to select a range
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,7 +19,7 @@ internal sealed class AspNetCoreInstrumentation : IDisposable
"Microsoft.AspNetCore.Hosting.UnhandledException"
];

private readonly Func<string, object?, object?, bool> isEnabled = (eventName, _, _)
private readonly Func<string, object?, object?, bool> isEnabled = static (eventName, _, _)
=> DiagnosticSourceEvents.Contains(eventName);

private readonly DiagnosticSourceSubscriber diagnosticSourceSubscriber;
Expand All @@ -32,7 +32,5 @@ public AspNetCoreInstrumentation(HttpInListener httpInListener)

/// <inheritdoc/>
public void Dispose()
{
this.diagnosticSourceSubscriber?.Dispose();
}
=> this.diagnosticSourceSubscriber?.Dispose();
}
Original file line number Diff line number Diff line change
Expand Up @@ -75,9 +75,7 @@ public static TracerProviderBuilder AddAspNetCoreInstrumentation(
return builder.AddInstrumentation(sp =>
{
var options = sp.GetRequiredService<IOptionsMonitor<AspNetCoreTraceInstrumentationOptions>>().Get(name);

return new AspNetCoreInstrumentation(
new HttpInListener(options));
return new AspNetCoreInstrumentation(new HttpInListener(options));
});
}

Expand All @@ -102,9 +100,9 @@ private static void AddAspNetCoreInstrumentationSources(
string optionsName,
IServiceProvider? serviceProvider = null)
{
// For .NET7.0 onwards activity will be created using activitySource.
// For .NET 7.0+ the activity will be created using activitySource.
// https://github.com/dotnet/aspnetcore/blob/bf3352f2422bf16fa3ca49021f0e31961ce525eb/src/Hosting/Hosting/src/Internal/HostingApplicationDiagnostics.cs#L327
// For .NET6.0 and below, we will continue to use legacy way.
// For .NET 6.0 and below, we will continue to use legacy way.
if (HttpInListener.Net7OrGreater)
{
// TODO: Check with .NET team to see if this can be prevented
Expand Down
6 changes: 6 additions & 0 deletions src/OpenTelemetry.Instrumentation.AspNetCore/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,12 @@

## Unreleased

* Avoid duplicative work to add tags to traces when they are already natively supported
by ASP.NET Core itself. When using ASP.NET Core 10, performance can be
improved by setting the `Microsoft.AspNetCore.Hosting.SuppressActivityOpenTelemetryData`
AppContext switch to `false` (its default value is `true`).
([#3993](https://github.com/open-telemetry/opentelemetry-dotnet-contrib/pull/3993))

## 1.15.2

Released 2026-Apr-21
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ internal class HttpInListener : ListenerHandler
#pragma warning restore IDE0370 // Suppression is unnecessary
internal static readonly ActivitySource ActivitySource = new(ActivitySourceName, Version.ToString());
internal static readonly bool Net7OrGreater = Environment.Version.Major >= 7;
internal static readonly bool Net10OrGreater = Environment.Version.Major >= 10;

private const string DiagnosticSourceName = "Microsoft.AspNetCore";

Expand All @@ -47,13 +48,15 @@ internal class HttpInListener : ListenerHandler
private static readonly PropertyFetcher<Exception> ExceptionPropertyFetcher = new("Exception");

private readonly AspNetCoreTraceInstrumentationOptions options;
private readonly bool nativeAspNetCoreOpenTelemetryEnabled;

public HttpInListener(AspNetCoreTraceInstrumentationOptions options)
: base(DiagnosticSourceName)
{
Guard.ThrowIfNull(options);

this.options = options;
this.nativeAspNetCoreOpenTelemetryEnabled = AspNetCoreHasNativeOpenTelemetryTags();
}

public override void OnEventWritten(string name, object? payload)
Expand All @@ -63,24 +66,18 @@ public override void OnEventWritten(string name, object? payload)
switch (name)
{
case OnStartEvent:
{
this.OnStartActivity(activity, payload);
}

this.OnStartActivity(activity, payload);
break;
case OnStopEvent:
{
this.OnStopActivity(activity, payload);
}

case OnStopEvent:
this.OnStopActivity(activity, payload);
break;

case OnUnhandledHostingExceptionEvent:
case OnUnHandledDiagnosticsExceptionEvent:
{
this.OnException(activity, payload);
}

this.OnException(activity, payload);
break;

default:
break;
}
Expand Down Expand Up @@ -176,19 +173,38 @@ public void OnStartActivity(Activity activity, object? payload)
ActivityInstrumentationHelper.SetKindProperty(activity, ActivityKind.Server);
}

// See the spec: https://github.com/open-telemetry/semantic-conventions/blob/v1.40.0/docs/http/http-spans.md
var path = (request.PathBase.HasValue || request.Path.HasValue) ? (request.PathBase + request.Path).ToString() : "/";

TelemetryHelper.RequestDataHelper.SetActivityDisplayName(activity, request.Method);

// see the spec https://github.com/open-telemetry/semantic-conventions/blob/v1.23.0/docs/http/http-spans.md
// ASP.NET Core 10 does not support OTEL_INSTRUMENTATION_HTTP_KNOWN_METHODS so we
// still need to set the HTTP method tag so that any override by the user is honoured.
TelemetryHelper.RequestDataHelper.SetHttpMethodTag(activity, request.Method);

if (request.Host.HasValue)
if (!Net10OrGreater || !this.nativeAspNetCoreOpenTelemetryEnabled)
{
activity.SetTag(SemanticConventions.AttributeServerAddress, request.Host.Host);
if (request.Host.HasValue)
{
activity.SetTag(SemanticConventions.AttributeServerAddress, request.Host.Value);

if (request.Host.Port is { } port)
{
activity.SetTag(SemanticConventions.AttributeServerPort, port);
}
}

if (request.Host.Port.HasValue)
if (request.Headers.TryGetValue("User-Agent", out var values))
{
activity.SetTag(SemanticConventions.AttributeServerPort, request.Host.Port.Value);
var userAgent = values.Count > 0 ? values[0] : null;
if (!string.IsNullOrEmpty(userAgent))
{
activity.SetTag(SemanticConventions.AttributeUserAgentOriginal, userAgent);
}
}

activity.SetTag(SemanticConventions.AttributeUrlScheme, request.Scheme);
activity.SetTag(SemanticConventions.AttributeUrlPath, path);
}

if (request.QueryString.HasValue)
Expand All @@ -203,21 +219,8 @@ public void OnStartActivity(Activity activity, object? payload)
}
}

TelemetryHelper.RequestDataHelper.SetHttpMethodTag(activity, request.Method);

activity.SetTag(SemanticConventions.AttributeUrlScheme, request.Scheme);
activity.SetTag(SemanticConventions.AttributeUrlPath, path);
activity.SetTag(SemanticConventions.AttributeNetworkProtocolVersion, RequestDataHelper.GetHttpProtocolVersion(request.Protocol));

if (request.Headers.TryGetValue("User-Agent", out var values))
{
var userAgent = values.Count > 0 ? values[0] : null;
if (!string.IsNullOrEmpty(userAgent))
{
activity.SetTag(SemanticConventions.AttributeUserAgentOriginal, userAgent);
}
}

try
{
this.options.EnrichWithHttpRequest?.Invoke(activity, request);
Expand Down Expand Up @@ -394,4 +397,28 @@ private static void AddGrpcAttributes(Activity activity, string grpcMethod, Http
}
}
}

// ASP.NET Core 10 does not generate OpenTelemetry tags by default so we can only take
// the optimal path if the user has explicitly opted-out of suppressing the OpenTelemetry data.
private static bool AspNetCoreHasNativeOpenTelemetryTags()
{
#if NET10_0_OR_GREATER
if (AppContext.TryGetSwitch("Microsoft.AspNetCore.Hosting.SuppressActivityOpenTelemetryData", out var suppressed))
{
return !suppressed;
}
#endif
#if NET10_0
Comment thread
martincostello marked this conversation as resolved.
// In ASP.NET Core 10 OpenTelemetry tags are suppressed by default,
// see https://github.com/dotnet/aspnetcore/blob/7387de91234d3ef751fa50b3d1bfede4130213ff/src/Hosting/Hosting/src/Internal/HostingApplicationDiagnostics.cs#L59-L67.
return false;
#elif NET11_0_OR_GREATER
// In ASP.NET Core 11+ OpenTelemetry tags are emitted by default,
// see https://github.com/dotnet/aspnetcore/blob/655f41d52f2fc75992eac41496b8e9cc119e1b54/src/Hosting/Hosting/src/Internal/HostingApplicationDiagnostics.cs#L59-L67.
return true;
#else
// In ASP.NET Core 8 and 9 the feature switch does not exist and there are no native OpenTelemetry tags
return false;
#endif
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -725,7 +725,6 @@ public async Task ActivitiesStartedInMiddlewareBySettingHostActivityToNullShould
Assert.Equal("Microsoft.AspNetCore.Hosting.HttpRequestIn", aspnetcoreframeworkactivity.OperationName);
}

#if NET
[Fact]
public async Task UserRegisteredActivitySourceIsUsedForActivityCreationByAspNetCore()
{
Expand Down Expand Up @@ -766,7 +765,6 @@ void ConfigureTestServices(IServiceCollection services)

Assert.Equal("UserRegisteredActivitySource", activity.Source.Name);
}
#endif

[Theory]
[InlineData(1)]
Expand Down Expand Up @@ -1332,14 +1330,9 @@ private static void WaitForActivityExport(List<Activity> exportedItems, int coun
private static void ValidateAspNetCoreActivity(Activity activityToValidate, string expectedHttpPath)
{
Assert.Equal(ActivityKind.Server, activityToValidate.Kind);
#if NET
Assert.Equal(HttpInListener.AspNetCoreActivitySourceName, activityToValidate.Source.Name);
Assert.NotNull(activityToValidate.Source.Version);
Assert.Empty(activityToValidate.Source.Version);
#else
Assert.Equal(HttpInListener.ActivitySourceName, activityToValidate.Source.Name);
Assert.Equal(HttpInListener.Version.ToString(), activityToValidate.Source.Version);
#endif
Assert.Equal(expectedHttpPath, activityToValidate.GetTagValue(SemanticConventions.AttributeUrlPath) as string);
}

Expand Down
114 changes: 114 additions & 0 deletions test/OpenTelemetry.Instrumentation.AspNetCore.Tests/EndToEndTests.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,114 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0

using System.Diagnostics;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using OpenTelemetry.Instrumentation.AspNetCore.Implementation;
using OpenTelemetry.Trace;
using Xunit;

namespace OpenTelemetry.Instrumentation.AspNetCore.Tests;

[Collection("AspNetCore")]
public sealed class EndToEndTests
: IClassFixture<WebApplicationFactory<Program>>, IDisposable
{
private readonly WebApplicationFactory<Program> factory;
private TracerProvider? tracerProvider;

public EndToEndTests(WebApplicationFactory<Program> factory)
{
this.factory = factory;
}

[Theory]
[InlineData(false)]
[InlineData(true)]
public async Task HttpRequestActivityIsCorrectWithFeatureSwitch(bool isEnabled)
{
bool? originalValue = null;

if (AppContext.TryGetSwitch("Microsoft.AspNetCore.Hosting.SuppressActivityOpenTelemetryData", out var existingValue))
{
originalValue = existingValue;
}

AppContext.SetSwitch("Microsoft.AspNetCore.Hosting.SuppressActivityOpenTelemetryData", isEnabled);

try
{
var exportedItems = new List<Activity>();

void ConfigureTestServices(IServiceCollection services)
{
this.tracerProvider = Sdk.CreateTracerProviderBuilder()
.AddAspNetCoreInstrumentation()
.AddInMemoryExporter(exportedItems)
.Build();
}

// Arrange
using var client = this.factory
.WithWebHostBuilder(builder =>
{
builder.ConfigureTestServices(ConfigureTestServices);
builder.ConfigureLogging(loggingBuilder => loggingBuilder.ClearProviders());
})
.CreateClient();

client.DefaultRequestHeaders.UserAgent.Add(new("OpenTelemetry.Instrumentation.AspNetCore.Tests", "1.0"));

_ = await client.GetStringAsync(new Uri("/ping", UriKind.Relative));

WaitForActivityExport(exportedItems, 1);

var activity = Assert.Single(exportedItems);

ValidateAspNetCoreActivity(activity, "/ping");

Assert.Equal("GET /ping", activity.DisplayName);
Assert.Equal("GET", activity.GetTagValue(SemanticConventions.AttributeHttpRequestMethod));
Assert.Equal("localhost", activity.GetTagValue(SemanticConventions.AttributeServerAddress));
Assert.Equal("OpenTelemetry.Instrumentation.AspNetCore.Tests/1.0", activity.GetTagValue(SemanticConventions.AttributeUserAgentOriginal));
Assert.Equal("http", activity.GetTagValue(SemanticConventions.AttributeUrlScheme));
Assert.Equal("/ping", activity.GetTagValue(SemanticConventions.AttributeUrlPath));
}
finally
{
if (originalValue is { } previousValue)
{
AppContext.SetSwitch("Microsoft.AspNetCore.Hosting.SuppressActivityOpenTelemetryData", previousValue);
}
}
}

public void Dispose()
=> this.tracerProvider?.Dispose();

private static void WaitForActivityExport(List<Activity> exportedItems, int count)
=> Assert.True(
SpinWait.SpinUntil(
() =>
{
// We need to let End callback execute as it is executed AFTER response was returned.
// In unit tests environment there may be a lot of parallel unit tests executed, so
// giving some breathing room for the End callback to complete
Thread.Sleep(10);
return exportedItems.Count >= count;
},
TimeSpan.FromSeconds(5)),
$"Actual: {exportedItems.Count} Expected: {count}");

private static void ValidateAspNetCoreActivity(Activity activityToValidate, string expectedHttpPath)
{
Assert.Equal(ActivityKind.Server, activityToValidate.Kind);
Assert.Equal(HttpInListener.AspNetCoreActivitySourceName, activityToValidate.Source.Name);
Assert.NotNull(activityToValidate.Source.Version);
Assert.Empty(activityToValidate.Source.Version);
Assert.Equal(expectedHttpPath, activityToValidate.GetTagValue(SemanticConventions.AttributeUrlPath) as string);
}
}
Original file line number Diff line number Diff line change
@@ -1,22 +1,14 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0

#if NET
using System.Threading.RateLimiting;
using Microsoft.AspNetCore.Builder;
#endif
using Microsoft.AspNetCore.Hosting;
#if NET
using Microsoft.AspNetCore.Http;
#endif
using Microsoft.AspNetCore.Mvc.Testing;
#if NET
using Microsoft.AspNetCore.RateLimiting;
#endif
#if NET
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
#endif
using Microsoft.Extensions.Logging;
using OpenTelemetry.Metrics;
using OpenTelemetry.Trace;
Expand All @@ -38,7 +30,6 @@ public void AddAspNetCoreInstrumentation_BadArgs()
Assert.Throws<ArgumentNullException>(builder!.AddAspNetCoreInstrumentation);
}

#if NET
[Fact]
public async Task ValidateNetMetricsAsync()
{
Expand Down Expand Up @@ -178,7 +169,6 @@ static string GetTicks()

await app.DisposeAsync();
}
#endif

[Theory]
[InlineData("/api/values/2", "api/Values/{id}", null, 200)]
Expand Down
Loading
Loading