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

[Core] Updating System.Diagnostics.DiagnosticSource types usage #37661

Merged
merged 4 commits into from
Jul 19, 2023
Merged
Show file tree
Hide file tree
Changes from all 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 @@ -143,13 +143,20 @@ private static ValueTask ProcessNextAsync(HttpMessage message, ReadOnlyMemory<Ht
if (currentActivity != null)
{
var currentActivityId = currentActivity.Id ?? string.Empty;

#if NETCOREAPP2_1
if (currentActivity.IsW3CFormat())
#else
if (currentActivity.IdFormat == ActivityIdFormat.W3C)
#endif
{
if (!message.Request.Headers.Contains(TraceParentHeaderName))
{
message.Request.Headers.Add(TraceParentHeaderName, currentActivityId);
#if NETCOREAPP2_1
if (currentActivity.GetTraceState() is string traceStateString)
JoshLove-msft marked this conversation as resolved.
Show resolved Hide resolved
#else
if (currentActivity.TraceStateString is string traceStateString)
#endif
{
message.Request.Headers.Add(TraceStateHeaderName, traceStateString);
}
Expand Down Expand Up @@ -177,8 +184,16 @@ private static ValueTask ProcessNextAsync(HttpMessage message, ReadOnlyMemory<Ht

private bool ShouldCreateActivity =>
_isDistributedTracingEnabled &&
#if NETCOREAPP2_1
(s_diagnosticSource.IsEnabled() || ActivityExtensions.ActivitySourceHasListeners(s_activitySource));
#else
(s_diagnosticSource.IsEnabled() || s_activitySource.HasListeners());
#endif

#if NETCOREAPP2_1
private bool IsActivitySourceEnabled => _isDistributedTracingEnabled && ActivityExtensions.ActivitySourceHasListeners(s_activitySource);
#else
private bool IsActivitySourceEnabled => _isDistributedTracingEnabled && s_activitySource.HasListeners();
#endif
}
}
143 changes: 139 additions & 4 deletions sdk/core/Azure.Core/src/Shared/DiagnosticScope.cs
Original file line number Diff line number Diff line change
Expand Up @@ -31,10 +31,20 @@ internal DiagnosticScope(string scopeName, DiagnosticListener source, object? di
#endif
{
// ActivityKind.Internal and Client both can represent public API calls depending on the SDK
#if NETCOREAPP2_1
_suppressNestedClientActivities = (kind == ActivityKind.Client || kind == ActivityKind.Internal) ? suppressNestedClientActivities : false;
#else
_suppressNestedClientActivities = (kind == ActivityKind.Client || kind == System.Diagnostics.ActivityKind.Internal) ? suppressNestedClientActivities : false;
#endif

// outer scope presence is enough to suppress any inner scope, regardless of inner scope configuation.
IsEnabled = source.IsEnabled() || ActivityExtensions.ActivitySourceHasListeners(activitySource);
bool hasListeners;
#if NETCOREAPP2_1
hasListeners = ActivityExtensions.ActivitySourceHasListeners(activitySource);
#else
hasListeners = activitySource?.HasListeners() ?? false;
#endif
IsEnabled = source.IsEnabled() || hasListeners;

if (_suppressNestedClientActivities)
{
Expand Down Expand Up @@ -178,23 +188,39 @@ public DiagnosticActivity(string operationName) : base(operationName)

private class ActivityAdapter : IDisposable
{
#if NETCOREAPP2_1
private readonly object? _activitySource;
#else
private readonly ActivitySource? _activitySource;
#endif
private readonly DiagnosticSource _diagnosticSource;
private readonly string _activityName;
#if NETCOREAPP2_1
private readonly ActivityKind _kind;
#else
private readonly System.Diagnostics.ActivityKind _kind;
#endif
private readonly object? _diagnosticSourceArgs;

private Activity? _currentActivity;
private Activity? _sampleOutActivity;

#if NETCOREAPP2_1
private ICollection<KeyValuePair<string,object>>? _tagCollection;
#else
private ActivityTagsCollection? _tagCollection;
#endif
private DateTimeOffset _startTime;
private List<Activity>? _links;
private string? _traceparent;
private string? _tracestate;
private string? _displayName;

#if NETCOREAPP2_1
public ActivityAdapter(object? activitySource, DiagnosticSource diagnosticSource, string activityName, ActivityKind kind, object? diagnosticSourceArgs)
#else
public ActivityAdapter(ActivitySource? activitySource, DiagnosticSource diagnosticSource, string activityName, System.Diagnostics.ActivityKind kind, object? diagnosticSourceArgs)
#endif
{
_activitySource = activitySource;
_diagnosticSource = diagnosticSource;
Expand All @@ -209,30 +235,48 @@ public void AddTag(string name, object value)
{
// Activity is not started yet, add the value to the collection
// that is going to be passed to StartActivity
#if NETCOREAPP2_1
_tagCollection ??= ActivityExtensions.CreateTagsCollection() ?? new List<KeyValuePair<string, object>>();
_tagCollection?.Add(new KeyValuePair<string, object>(name, value!));
#else
_tagCollection ??= new ActivityTagsCollection();
_tagCollection.Add(name, value!);
#endif
}
else
{
#if NETCOREAPP2_1
_currentActivity?.AddObjectTag(name, value);
#else
_currentActivity?.AddTag(name, value);
#endif
}
}

#if NETCOREAPP2_1
private IList? GetActivitySourceLinkCollection()
#else
private List<ActivityLink>? GetActivitySourceLinkCollection()
#endif
{
if (_links == null)
{
return null;
}

#if NETCOREAPP2_1
var linkCollection = ActivityExtensions.CreateLinkCollection();
if (linkCollection == null)
{
return null;
}
#else
var linkCollection = new List<ActivityLink>();
#endif

foreach (var activity in _links)
{
#if NETCOREAPP2_1
ICollection<KeyValuePair<string,object>>? linkTagsCollection = ActivityExtensions.CreateTagsCollection();
if (linkTagsCollection != null)
{
Expand All @@ -247,17 +291,36 @@ public void AddTag(string name, object value)
{
linkCollection.Add(link);
}
}
#else
ActivityTagsCollection linkTagsCollection = new();
foreach (var tag in activity.Tags)
{
linkTagsCollection.Add(tag.Key, tag.Value!);
}

var contextWasParsed = ActivityContext.TryParse(activity.ParentId!, activity.TraceStateString, out var context);
if (contextWasParsed)
{
var link = new ActivityLink(context, linkTagsCollection);
linkCollection.Add(link);
}
#endif
}

return linkCollection;
}

public void AddLink(string traceparent, string? tracestate, IDictionary<string, string>? attributes)
{
var linkedActivity = new Activity("LinkedActivity");
linkedActivity.SetW3CFormat();
linkedActivity.SetParentId(traceparent);
#if NETCOREAPP2_1
linkedActivity.SetW3CFormat();
linkedActivity.SetTraceState(tracestate);
#else
linkedActivity.SetIdFormat(ActivityIdFormat.W3C);
linkedActivity.TraceStateString = tracestate;
#endif

if (attributes != null)
{
Expand All @@ -276,7 +339,11 @@ public void AddLink(string traceparent, string? tracestate, IDictionary<string,
_currentActivity = StartActivitySourceActivity();
if (_currentActivity != null)
{
#if NETCOREAPP2_1
if (!_currentActivity.GetIsAllDataRequested())
#else
if (!_currentActivity.IsAllDataRequested)
#endif
{
_sampleOutActivity = _currentActivity;
_currentActivity = null;
Expand Down Expand Up @@ -316,7 +383,11 @@ public void AddLink(string traceparent, string? tracestate, IDictionary<string,
{
Links = (IEnumerable<Activity>?)_links ?? Array.Empty<Activity>(),
};
#if NETCOREAPP2_1
_currentActivity.SetW3CFormat();
#else
_currentActivity.SetIdFormat(ActivityIdFormat.W3C);
#endif

if (_startTime != default)
{
Expand All @@ -327,7 +398,11 @@ public void AddLink(string traceparent, string? tracestate, IDictionary<string,
{
foreach (var tag in _tagCollection)
{
#if NETCOREAPP2_1
_currentActivity.AddObjectTag(tag.Key, tag.Value);
#else
_currentActivity.AddTag(tag.Key, tag.Value);
#endif
}
}

Expand All @@ -338,7 +413,11 @@ public void AddLink(string traceparent, string? tracestate, IDictionary<string,

if (_tracestate != null)
{
#if NETCOREAPP2_1
_currentActivity.SetTraceState(_tracestate);
#else
_currentActivity.TraceStateString = _tracestate;
#endif
}

_currentActivity.Start();
Expand All @@ -348,7 +427,11 @@ public void AddLink(string traceparent, string? tracestate, IDictionary<string,

if (_displayName != null)
{
#if NETCOREAPP2_1
_currentActivity?.SetDisplayName(_displayName);
#else
_currentActivity.DisplayName = _displayName;
#endif
}

return _currentActivity;
Expand All @@ -357,11 +440,19 @@ public void AddLink(string traceparent, string? tracestate, IDictionary<string,
public void SetDisplayName(string displayName)
{
_displayName = displayName;
_currentActivity?.SetDisplayName(displayName);
if (_currentActivity != null)
{
#if NETCOREAPP2_1
_currentActivity.SetDisplayName(_displayName);
#else
_currentActivity.DisplayName = _displayName;
#endif
}
}

private Activity? StartActivitySourceActivity()
{
#if NETCOREAPP2_1
return ActivityExtensions.ActivitySourceStartActivity(
_activitySource,
_activityName,
Expand All @@ -371,6 +462,23 @@ public void SetDisplayName(string displayName)
links: GetActivitySourceLinkCollection(),
traceparent: _traceparent,
tracestate: _tracestate);
#else
if (_activitySource == null)
{
return null;
}
ActivityContext context;
if (_traceparent != null)
{
context = ActivityContext.Parse(_traceparent, _tracestate);
}
else
{
context = new ActivityContext();
}
var activity = _activitySource.StartActivity(_activityName, _kind, context, _tagCollection, GetActivitySourceLinkCollection()!, _startTime);
return activity;
#endif
}

public void SetStartTime(DateTime startTime)
Expand All @@ -386,10 +494,15 @@ public void MarkFailed(Exception? exception)
_diagnosticSource?.Write(_activityName + ".Exception", exception);
}

#if NETCOREAPP2_1
if (ActivityExtensions.SupportsActivitySource())
{
_currentActivity?.SetErrorStatus(exception?.ToString());
}
#endif
#if NET6_0_OR_GREATER
m-redding marked this conversation as resolved.
Show resolved Hide resolved
_currentActivity?.SetStatus(ActivityStatusCode.Error, exception?.ToString());
#endif
}

public void SetTraceContext(string traceparent, string? tracestate)
Expand All @@ -415,14 +528,19 @@ public void Dispose()

_diagnosticSource.Write(_activityName + ".Stop", _diagnosticSourceArgs);

#if NETCOREAPP2_1
if (!activity.TryDispose())
{
activity.Stop();
}
#else
activity.Dispose();
#endif
}
}
}

#if NETCOREAPP2_1
#pragma warning disable SA1507 // File can not contain multiple types
/// <summary>
/// Until we can reference the 5.0 of System.Diagnostics.DiagnosticSource
Expand Down Expand Up @@ -918,4 +1036,21 @@ public static void ResetFeatureSwitch()
"AZURE_EXPERIMENTAL_ENABLE_ACTIVITY_SOURCE");
}
}
#else
#pragma warning disable SA1507 // File can not contain multiple types
annelo-msft marked this conversation as resolved.
Show resolved Hide resolved
/// <summary>
/// Until Activity Source is no longer considered experimental.
m-redding marked this conversation as resolved.
Show resolved Hide resolved
/// </summary>
internal static class ActivityExtensions
{
public static bool SupportsActivitySource { get; private set; }

public static void ResetFeatureSwitch()
m-redding marked this conversation as resolved.
Show resolved Hide resolved
{
SupportsActivitySource = AppContextSwitchHelper.GetConfigValue(
"Azure.Experimental.EnableActivitySource",
"AZURE_EXPERIMENTAL_ENABLE_ACTIVITY_SOURCE");
}
}
#endif
}
4 changes: 4 additions & 0 deletions sdk/core/Azure.Core/src/Shared/DiagnosticScopeFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,11 @@ public DiagnosticScope CreateScope(string name, System.Diagnostics.ActivityKind
private static ActivitySource? GetActivitySource(string ns, string name)
#endif
{
#if NETCOREAPP2_1
if (!ActivityExtensions.SupportsActivitySource())
#else
if (!ActivityExtensions.SupportsActivitySource)
#endif
{
return null;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ public DiagnosticScope CreateScope(
MessagingDiagnosticOperation operation = default)
{
DiagnosticScope scope = _scopeFactory.CreateScope(activityName, kind);
if (ActivityExtensions.SupportsActivitySource())
if (ActivityExtensions.SupportsActivitySource)
{
scope.AddAttribute(MessagingSystem, _messagingSystem);
if (operation != default)
Expand Down Expand Up @@ -99,7 +99,7 @@ public static bool TryExtractTraceContext(IReadOnlyDictionary<string, object> pr
traceparent = null;
tracestate = null;

if (ActivityExtensions.SupportsActivitySource() && properties.TryGetValue(TraceParent, out var traceParent) && traceParent is string traceParentString)
if (ActivityExtensions.SupportsActivitySource && properties.TryGetValue(TraceParent, out var traceParent) && traceParent is string traceParentString)
{
traceparent = traceParentString;
if (properties.TryGetValue(TraceState, out object state) && state is string stateString)
Expand Down Expand Up @@ -131,7 +131,7 @@ public static bool TryExtractTraceContext(IDictionary<string, object> properties
traceparent = null;
tracestate = null;

if (ActivityExtensions.SupportsActivitySource() && properties.TryGetValue(TraceParent, out var traceParent) && traceParent is string traceParentString)
if (ActivityExtensions.SupportsActivitySource && properties.TryGetValue(TraceParent, out var traceParent) && traceParent is string traceParentString)
{
traceparent = traceParentString;
if (properties.TryGetValue(TraceState, out object state) && state is string stateString)
Expand Down Expand Up @@ -175,7 +175,7 @@ public void InstrumentMessage(IDictionary<string, object> properties, string act
{
traceparent = activity.Id!;
properties[DiagnosticIdAttribute] = traceparent;
if (ActivityExtensions.SupportsActivitySource())
if (ActivityExtensions.SupportsActivitySource)
{
properties[TraceParent] = traceparent;
if (activity.TraceStateString != null)
Expand Down
Loading