Skip to content
Open
Show file tree
Hide file tree
Changes from 5 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,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
5 changes: 5 additions & 0 deletions src/OpenTelemetry.Instrumentation.AspNetCore/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,11 @@

* The value of the `http.route` attribute is now aligned with ASP.NET Core itself.
([#3992](https://github.com/open-telemetry/opentelemetry-dotnet-contrib/pull/3992))
* 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))

* Updated OpenTelemetry core component version(s) to `1.15.1`.
([#4020](https://github.com/open-telemetry/opentelemetry-dotnet-contrib/pull/4020))
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 nativeAspNetCoreOpenTelemetrySuppressed;

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

this.options = options;
this.nativeAspNetCoreOpenTelemetrySuppressed = IsOpenTelemetryActivityDataSuppressed();
}

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.nativeAspNetCoreOpenTelemetrySuppressed)
{
activity.SetTag(SemanticConventions.AttributeServerAddress, request.Host.Host);
if (request.Host is { } host)
{
activity.SetTag(SemanticConventions.AttributeServerAddress, host.Host);

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,15 @@ 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 not explicitly opened into ASP.NET Core 10's native OpenTelemetry support.
Copy link

Copilot AI Mar 27, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Typo: "opened into" should be "opted into".

Suggested change
// path if the user has not explicitly opened into ASP.NET Core 10's native OpenTelemetry support.
// path if the user has not explicitly opted into ASP.NET Core 10's native OpenTelemetry support.

Copilot uses AI. Check for mistakes.
Copy link

Copilot AI Mar 27, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The comment about when the "optimal path" is taken appears inverted. The code skips manual tag population only when native OpenTelemetry data is not suppressed (i.e., the suppress switch is set to false), so the comment should reflect that this path is only valid when the user has explicitly enabled ASP.NET Core's native OpenTelemetry tags.

Suggested change
// ASP.NET Core 10 does not generate OpenTelemetry tags by default so we can only take the optimal
// path if the user has not explicitly opened into ASP.NET Core 10's native OpenTelemetry support.
// 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 into ASP.NET Core 10's native OpenTelemetry support.

Copilot uses AI. Check for mistakes.
// https://github.com/dotnet/aspnetcore/blob/7387de91234d3ef751fa50b3d1bfede4130213ff/src/Hosting/Hosting/src/Internal/HostingApplicationDiagnostics.cs#L58-L67

private static bool IsOpenTelemetryActivityDataSuppressed() =>
#if NET10_0
Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This isn't _OR_GREATER as .NET 11 swaps the default to false.

!AppContext.TryGetSwitch("Microsoft.AspNetCore.Hosting.SuppressActivityOpenTelemetryData", out var enabled) || enabled;
Copy link
Copy Markdown
Member Author

@martincostello martincostello Mar 19, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'll (try to) add tests to validate this scenario if everyone is happy with the change in principle.

#else
false;
#endif
}
Loading