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

[Instrumentation.AspNetCore] .NET6 library works on .NET7 and .NET8 #5252

Merged
Merged
Show file tree
Hide file tree
Changes from 3 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 @@ -27,6 +27,11 @@ public static MeterProviderBuilder AddAspNetCoreInstrumentation(
#if NET8_0_OR_GREATER
return builder.ConfigureMeters();
#else
if (Environment.Version.Major >= 8)
Kielek marked this conversation as resolved.
Show resolved Hide resolved
{
return builder.ConfigureMeters();
}

// Note: Warm-up the status code and method mapping.
_ = TelemetryHelper.BoxedStatusCodes;
_ = RequestMethodHelper.KnownMethods;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0

#if NET7_0_OR_GREATER
using System.Diagnostics;
#endif
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Options;
using OpenTelemetry.Instrumentation.AspNetCore;
Expand Down Expand Up @@ -101,7 +99,11 @@ private static void AddAspNetCoreInstrumentationSources(
// For .NET7.0 onwards 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.
#if NET7_0_OR_GREATER

#if !NET7_0_OR_GREATER
if (HttpInListener.Net7OrGreater)
{
#endif
// TODO: Check with .NET team to see if this can be prevented
// as this allows user to override the ActivitySource.
var activitySourceService = serviceProvider?.GetService<ActivitySource>();
Expand All @@ -114,9 +116,13 @@ private static void AddAspNetCoreInstrumentationSources(
// For users not using hosting package?
builder.AddSource(HttpInListener.AspNetCoreActivitySourceName);
}
#else
builder.AddSource(HttpInListener.ActivitySourceName);
builder.AddLegacySource(HttpInListener.ActivityOperationName); // for the activities created by AspNetCore
#if !NET7_0_OR_GREATER
}
else
{
builder.AddSource(HttpInListener.ActivitySourceName);
builder.AddLegacySource(HttpInListener.ActivityOperationName); // for the activities created by AspNetCore
}
#endif
}
}
8 changes: 7 additions & 1 deletion src/OpenTelemetry.Instrumentation.AspNetCore/CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,13 @@
[#4466](https://github.com/open-telemetry/opentelemetry-dotnet/issues/4466)
where the activity instance returned by `Activity.Current` was different than
instance obtained from `IHttpActivityFeature.Activity`.
[#5136](https://github.com/open-telemetry/opentelemetry-dotnet/pull/5136)
([#5136](https://github.com/open-telemetry/opentelemetry-dotnet/pull/5136))

* Fixed metrics instrumentation when library targeting .NET 6 or .NET 7
was loaded by .NET 8.
Fixed traces instrumentation when library targeting .NET 6
was loaded by .NET 7 or .NET 8.
([#5252](https://github.com/open-telemetry/opentelemetry-dotnet/pull/5252))

## 1.7.0

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,16 +26,18 @@ internal class HttpInListener : ListenerHandler
internal const string OnUnhandledHostingExceptionEvent = "Microsoft.AspNetCore.Hosting.UnhandledException";
internal const string OnUnHandledDiagnosticsExceptionEvent = "Microsoft.AspNetCore.Diagnostics.UnhandledException";

#if NET7_0_OR_GREATER
// https://github.com/dotnet/aspnetcore/blob/8d6554e655b64da75b71e0e20d6db54a3ba8d2fb/src/Hosting/Hosting/src/GenericHost/GenericWebHostBuilder.cs#L85
internal static readonly string AspNetCoreActivitySourceName = "Microsoft.AspNetCore";
#endif

internal static readonly AssemblyName AssemblyName = typeof(HttpInListener).Assembly.GetName();
internal static readonly string ActivitySourceName = AssemblyName.Name;
internal static readonly Version Version = AssemblyName.Version;
internal static readonly ActivitySource ActivitySource = new(ActivitySourceName, Version.ToString());

#if !NET7_0_OR_GREATER
internal static readonly bool Net7OrGreater = Environment.Version.Major >= 7;
#endif

private const string DiagnosticSourceName = "Microsoft.AspNetCore";

private static readonly Func<HttpRequest, string, IEnumerable<string>> HttpRequestHeaderValuesGetter = (request, name) =>
Expand Down Expand Up @@ -120,14 +122,24 @@ public void OnStartActivity(Activity activity, object payload)
// Create a new activity with its parent set from the extracted context.
// This makes the new activity as a "sibling" of the activity created by
// Asp.Net Core.
#if NET7_0_OR_GREATER
Activity newOne;
#if !NET7_0_OR_GREATER
if (Net7OrGreater)
{
#endif

// For NET7.0 onwards activity is created using ActivitySource so,
// we will use the source of the activity to create the new one.
Activity newOne = activity.Source.CreateActivity(ActivityOperationName, ActivityKind.Server, ctx.ActivityContext);
#else
Activity newOne = new Activity(ActivityOperationName);
newOne.SetParentId(ctx.ActivityContext.TraceId, ctx.ActivityContext.SpanId, ctx.ActivityContext.TraceFlags);
newOne = activity.Source.CreateActivity(ActivityOperationName, ActivityKind.Server, ctx.ActivityContext);
#if !NET7_0_OR_GREATER
}
else
{
newOne = new Activity(ActivityOperationName);
newOne.SetParentId(ctx.ActivityContext.TraceId, ctx.ActivityContext.SpanId, ctx.ActivityContext.TraceFlags);
}
#endif

newOne.TraceStateString = ctx.ActivityContext.TraceState;

newOne.SetTag("IsCreatedByInstrumentation", bool.TrueString);
Expand Down Expand Up @@ -166,8 +178,11 @@ public void OnStartActivity(Activity activity, object payload)
}

#if !NET7_0_OR_GREATER
ActivityInstrumentationHelper.SetActivitySourceProperty(activity, ActivitySource);
ActivityInstrumentationHelper.SetKindProperty(activity, ActivityKind.Server);
if (!Net7OrGreater)
{
ActivityInstrumentationHelper.SetActivitySourceProperty(activity, ActivitySource);
ActivityInstrumentationHelper.SetKindProperty(activity, ActivityKind.Server);
}
#endif

var path = (request.PathBase.HasValue || request.Path.HasValue) ? (request.PathBase + request.Path).ToString() : "/";
Expand Down Expand Up @@ -261,12 +276,8 @@ public void OnStopActivity(Activity activity, object payload)
}
}

#if NET7_0_OR_GREATER
var tagValue = activity.GetTagValue("IsCreatedByInstrumentation");
if (ReferenceEquals(tagValue, bool.TrueString))
#else
Kielek marked this conversation as resolved.
Show resolved Hide resolved
if (activity.TryCheckFirstTag("IsCreatedByInstrumentation", out var tagValue) && ReferenceEquals(tagValue, bool.TrueString))
#endif
{
// If instrumentation started a new Activity, it must
// be stopped here.
Expand Down
29 changes: 0 additions & 29 deletions src/Shared/ActivityHelperExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -83,33 +83,4 @@ public static bool TryGetStatus(this Activity activity, out StatusCode statusCod

return null;
}

/// <summary>
/// Checks if the user provided tag name is the first tag of the <see cref="Activity"/> and retrieves the tag value.
/// </summary>
/// <param name="activity">Activity instance.</param>
/// <param name="tagName">Tag name.</param>
/// <param name="tagValue">Tag value.</param>
/// <returns><see langword="true"/> if the first tag of the supplied Activity matches the user provide tag name.</returns>
[MethodImpl(MethodImplOptions.AggressiveInlining)]
public static bool TryCheckFirstTag(this Activity activity, string tagName, out object? tagValue)
{
Debug.Assert(activity != null, "Activity should not be null");

var enumerator = activity!.EnumerateTagObjects();

if (enumerator.MoveNext())
{
ref readonly var tag = ref enumerator.Current;

if (tag.Key == tagName)
{
tagValue = tag.Value;
return true;
}
}

tagValue = null;
return false;
}
}
23 changes: 0 additions & 23 deletions test/OpenTelemetry.Api.Tests/Trace/ActivityExtensionsTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -198,27 +198,4 @@ public void GetTagValue()
Assert.Null(activity.GetTagValue("tag1"));
Assert.Null(activity.GetTagValue("Tag2"));
}

[Theory]
[InlineData("Key", "Value", true)]
[InlineData("CustomTag", null, false)]
public void TryCheckFirstTag(string tagName, object expectedTagValue, bool expectedResult)
{
using var activity = new Activity("Test");
activity.SetTag("Key", "Value");

var result = activity.TryCheckFirstTag(tagName, out var tagValue);
Assert.Equal(expectedResult, result);
Assert.Equal(expectedTagValue, tagValue);
}

[Fact]
public void TryCheckFirstTagReturnsFalseForActivityWithNoTags()
{
using var activity = new Activity("Test");

var result = activity.TryCheckFirstTag("Key", out var tagValue);
Assert.False(result);
Assert.Null(tagValue);
}
}
Loading