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 9 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 @@ -6,7 +6,7 @@
[#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 an issue where the `http.route` attribute was not set on either the
`Activity` or `http.server.request.duration` metric generated from a
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -27,10 +27,8 @@ 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;
Expand All @@ -39,6 +37,8 @@ internal class HttpInListener : ListenerHandler

private const string DiagnosticSourceName = "Microsoft.AspNetCore";

private static readonly bool Net7OrGreater = Environment.Version.Major >= 7;
Kielek marked this conversation as resolved.
Show resolved Hide resolved

private static readonly Func<HttpRequest, string, IEnumerable<string>> HttpRequestHeaderValuesGetter = (request, name) =>
{
if (request.Headers.TryGetValue(name, out var value))
Expand Down Expand Up @@ -121,14 +121,19 @@ 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
// 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);
#endif
Activity newOne;
if (Net7OrGreater)
{
// For NET7.0 onwards activity is created using ActivitySource so,
// we will use the source of the activity to create the new one.
newOne = activity.Source.CreateActivity(ActivityOperationName, ActivityKind.Server, ctx.ActivityContext);
}
else
{
newOne = new Activity(ActivityOperationName);
newOne.SetParentId(ctx.ActivityContext.TraceId, ctx.ActivityContext.SpanId, ctx.ActivityContext.TraceFlags);
}

newOne.TraceStateString = ctx.ActivityContext.TraceState;

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

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

var path = (request.PathBase.HasValue || request.Path.HasValue) ? (request.PathBase + request.Path).ToString() : "/";
activity.DisplayName = GetDisplayName(request.Method);
Expand Down Expand Up @@ -263,12 +269,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);
}
}