Skip to content
Closed
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 @@ -4,4 +4,9 @@
<method signature="System.Boolean get_Enabled()" body="stub" value="false" />
</type>
</assembly>
<assembly fullname="System.Diagnostics.DiagnosticSource" feature="System.Diagnostics.ActivitySource.IsSupported" featurevalue="false">
<type fullname="System.Diagnostics.ActivitySource">
<method signature="System.Boolean HasListeners()" body="stub" value="false" />
</type>
</assembly>
</linker>
Original file line number Diff line number Diff line change
Expand Up @@ -55,13 +55,11 @@ internal ActivityChangedEventArgs(Activity? previous, Activity? current)
/// </summary>
public partial class Activity : IDisposable
{
#pragma warning disable CA1825 // Array.Empty<T>() doesn't exist in all configurations
private static readonly IEnumerable<KeyValuePair<string, string?>> s_emptyBaggageTags = new KeyValuePair<string, string?>[0];
private static readonly IEnumerable<KeyValuePair<string, object?>> s_emptyTagObjects = new KeyValuePair<string, object?>[0];
private static readonly IEnumerable<ActivityLink> s_emptyLinks = new DiagLinkedList<ActivityLink>();
private static readonly IEnumerable<ActivityEvent> s_emptyEvents = new DiagLinkedList<ActivityEvent>();
#pragma warning restore CA1825
private static readonly ActivitySource s_defaultSource = new ActivitySource(string.Empty);
private static readonly IEnumerable<KeyValuePair<string, string?>> s_emptyBaggageTags = [];
private static readonly IEnumerable<KeyValuePair<string, object?>> s_emptyTagObjects = [];
private static readonly IEnumerable<ActivityLink> s_emptyLinks = [];
private static readonly IEnumerable<ActivityEvent> s_emptyEvents = [];
private static readonly ActivitySource? s_defaultSource = ActivitySource.IsSupported ? new ActivitySource(string.Empty) : null;
private static readonly AsyncLocal<Activity?> s_current = new AsyncLocal<Activity?>();

private const byte ActivityTraceFlagsIsSet = 0b_1_0000000; // Internal flag to indicate if flags have been set
Expand Down Expand Up @@ -453,7 +451,14 @@ public IEnumerable<ActivityLink> Links
/// <param name="operationName">Operation's name <see cref="OperationName"/></param>
public Activity(string operationName)
{
Source = s_defaultSource;
if (!ActivitySource.IsSupported)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Why does the linker see the Activity as instantiated so that you have to do this manually?

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.

regex /e=".*System.Diagnostics.Activity:: on artifacts\bin\trimmingTests\projects\System.Net.Http.TrimmingTests\DiagnosticsAndMetricsTrimmedTest\win-x64\obj\Release\net10.0\win-x64\linked\linker-dependencies.xml can find 34 member usages. Maybe this is not one of them and I was too defensive.

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.

I sent you the file in Teams

{
throw new NotSupportedException("Linked away");
}
else
{
Source = s_defaultSource!;
}
// Allow data by default in the constructor to keep the compatibility.
IsAllDataRequested = true;

Expand Down Expand Up @@ -485,6 +490,11 @@ public Activity(string operationName)
/// <param name="value">The tag value mapped to the input key</param>
public Activity AddTag(string key, object? value)
{
if (!ActivitySource.IsSupported)
{
throw new NotSupportedException("Linked away");
}

KeyValuePair<string, object?> kvp = new KeyValuePair<string, object?>(key, value);

if (_tags != null || Interlocked.CompareExchange(ref _tags, new TagsLinkedList(kvp), null) != null)
Expand All @@ -509,6 +519,11 @@ public Activity AddTag(string key, object? value)
/// <returns><see langword="this" /> for convenient chaining.</returns>
public Activity SetTag(string key, object? value)
{
if (!ActivitySource.IsSupported)
{
throw new NotSupportedException("Linked away");
}

KeyValuePair<string, object?> kvp = new KeyValuePair<string, object?>(key, value);

if (_tags != null || Interlocked.CompareExchange(ref _tags, new TagsLinkedList(kvp, set: true), null) != null)
Expand All @@ -526,6 +541,11 @@ public Activity SetTag(string key, object? value)
/// <returns><see langword="this" /> for convenient chaining.</returns>
public Activity AddEvent(ActivityEvent e)
{
if (!ActivitySource.IsSupported)
{
throw new NotSupportedException("Linked away");
}

if (_events != null || Interlocked.CompareExchange(ref _events, new DiagLinkedList<ActivityEvent>(e), null) != null)
{
_events.Add(e);
Expand All @@ -551,8 +571,11 @@ public Activity AddEvent(ActivityEvent e)
/// </remarks>
public Activity AddException(Exception exception, in TagList tags = default, DateTimeOffset timestamp = default)
{
if (!ActivitySource.IsSupported)
{
throw new NotSupportedException("Linked away");
}
ArgumentNullException.ThrowIfNull(exception);

TagList exceptionTags = tags;

Source.NotifyActivityAddException(this, exception, ref exceptionTags);
Expand Down Expand Up @@ -611,6 +634,11 @@ public Activity AddException(Exception exception, in TagList tags = default, Dat
/// </remarks>
public Activity AddLink(ActivityLink link)
{
if (!ActivitySource.IsSupported)
{
throw new NotSupportedException("Linked away");
}

if (_links != null || Interlocked.CompareExchange(ref _links, new DiagLinkedList<ActivityLink>(link), null) != null)
{
_links.Add(link);
Expand All @@ -630,6 +658,11 @@ public Activity AddLink(ActivityLink link)
/// <returns><see langword="this" /> for convenient chaining.</returns>
public Activity AddBaggage(string key, string? value)
{
if (!ActivitySource.IsSupported)
{
throw new NotSupportedException("Linked away");
}

KeyValuePair<string, string?> kvp = new KeyValuePair<string, string?>(key, value);

if (_baggage != null || Interlocked.CompareExchange(ref _baggage, new BaggageLinkedList(kvp), null) != null)
Expand All @@ -654,6 +687,11 @@ public Activity AddBaggage(string key, string? value)
/// <returns><see langword="this" /> for convenient chaining.</returns>
public Activity SetBaggage(string key, string? value)
{
if (!ActivitySource.IsSupported)
{
throw new NotSupportedException("Linked away");
}

KeyValuePair<string, string?> kvp = new KeyValuePair<string, string?>(key, value);

if (_baggage != null || Interlocked.CompareExchange(ref _baggage, new BaggageLinkedList(kvp, set: true), null) != null)
Expand All @@ -675,6 +713,11 @@ public Activity SetBaggage(string key, string? value)
/// <param name="parentId">The id of the parent operation.</param>
public Activity SetParentId(string parentId)
{
if (!ActivitySource.IsSupported)
{
throw new NotSupportedException("Linked away");
}

if (_id != null || _spanId != null)
{
// Cannot set the parent on already started Activity.
Expand Down Expand Up @@ -705,6 +748,11 @@ public Activity SetParentId(string parentId)
/// </summary>
public Activity SetParentId(ActivityTraceId traceId, ActivitySpanId spanId, ActivityTraceFlags activityTraceFlags = ActivityTraceFlags.None)
{
if (!ActivitySource.IsSupported)
{
throw new NotSupportedException("Linked away");
}

if (_id != null || _spanId != null)
{
// Cannot set the parent on already started Activity.
Expand Down Expand Up @@ -735,6 +783,11 @@ public Activity SetParentId(ActivityTraceId traceId, ActivitySpanId spanId, Acti
/// <returns><see langword="this" /> for convenient chaining.</returns>
public Activity SetStartTime(DateTime startTimeUtc)
{
if (!ActivitySource.IsSupported)
{
throw new NotSupportedException("Linked away");
}

if (startTimeUtc.Kind != DateTimeKind.Utc)
{
NotifyError(new InvalidOperationException(SR.StartTimeNotUtc));
Expand All @@ -755,6 +808,11 @@ public Activity SetStartTime(DateTime startTimeUtc)
/// <returns><see langword="this" /> for convenient chaining.</returns>
public Activity SetEndTime(DateTime endTimeUtc)
{
if (!ActivitySource.IsSupported)
{
throw new NotSupportedException("Linked away");
}

if (endTimeUtc.Kind != DateTimeKind.Utc)
{
NotifyError(new InvalidOperationException(SR.EndTimeNotUtc));
Expand Down Expand Up @@ -788,6 +846,11 @@ public Activity SetEndTime(DateTime endTimeUtc)
/// <seealso cref="SetStartTime(DateTime)"/>
public Activity Start()
{
if (!ActivitySource.IsSupported)
{
throw new NotSupportedException("Linked away");
}

// Has the ID already been set (have we called Start()).
if (_id != null || _spanId != null)
{
Expand Down Expand Up @@ -844,6 +907,11 @@ public Activity Start()
/// <seealso cref="SetEndTime(DateTime)"/>
public void Stop()
{
if (!ActivitySource.IsSupported)
{
throw new NotSupportedException("Linked away");
}

if (_id == null && _spanId == null)
{
NotifyError(new InvalidOperationException(SR.ActivityNotStarted));
Expand Down Expand Up @@ -1176,6 +1244,10 @@ internal static Activity Create(ActivitySource source, string name, ActivityKind
IEnumerable<KeyValuePair<string, object?>>? tags, IEnumerable<ActivityLink>? links, DateTimeOffset startTime,
ActivityTagsCollection? samplerTags, ActivitySamplingResult request, bool startIt, ActivityIdFormat idFormat, string? traceState)
{
if (!ActivitySource.IsSupported)
{
throw new NotSupportedException("Linked away");
}
Activity activity = new Activity(name);

activity.Source = source;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@

using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Metrics;
using System.Runtime.CompilerServices;
using System.Threading;

Expand All @@ -14,6 +16,10 @@ public sealed class ActivitySource : IDisposable
private static readonly SynchronizedList<ActivityListener> s_allListeners = new SynchronizedList<ActivityListener>();
private SynchronizedList<ActivityListener>? _listeners;

[FeatureSwitchDefinition("System.Diagnostics.ActivitySource.IsSupported")]
internal static bool IsSupported { get; } = InitializeIsActivitySourceSupported();
private static bool InitializeIsActivitySourceSupported() => AppContext.TryGetSwitch("System.Diagnostics.ActivitySource.IsSupported", out bool isSupported) ? isSupported : true;

/// <summary>
/// Construct an ActivitySource object with the input name
/// </summary>
Expand Down Expand Up @@ -47,6 +53,10 @@ private ActivitySource(string name, string? version, IEnumerable<KeyValuePair<st
Name = name ?? throw new ArgumentNullException(nameof(name));
Version = version;
TelemetrySchemaUrl = telemetrySchemaUrl;
if (!IsSupported)
{
return;
}

// Sorting the tags to make sure the tags are always in the same order.
// Sorting can help in comparing the tags used for any scenario.
Expand All @@ -71,8 +81,10 @@ private ActivitySource(string name, string? version, IEnumerable<KeyValuePair<st
}
}
}, this);

GC.KeepAlive(DiagnosticSourceEventSource.Log);
if (Meter.IsEventSourceSupported)
{
GC.KeepAlive(DiagnosticSourceEventSource.Log);
}
}

/// <summary>
Expand Down Expand Up @@ -103,6 +115,10 @@ private ActivitySource(string name, string? version, IEnumerable<KeyValuePair<st
/// </summary>
public bool HasListeners()
{
if (!IsSupported)
{
return false;
}
SynchronizedList<ActivityListener>? listeners = _listeners;
return listeners != null && listeners.Count > 0;
}
Expand Down Expand Up @@ -203,6 +219,10 @@ public bool HasListeners()
private Activity? CreateActivity(string name, ActivityKind kind, ActivityContext context, string? parentId, IEnumerable<KeyValuePair<string, object?>>? tags,
IEnumerable<ActivityLink>? links, DateTimeOffset startTime, bool startIt = true, ActivityIdFormat idFormat = ActivityIdFormat.Unknown)
{
if (!IsSupported)
{
return null;
}
// _listeners can get assigned to null in Dispose.
SynchronizedList<ActivityListener>? listeners = _listeners;
if (listeners == null || listeners.Count == 0)
Expand Down Expand Up @@ -336,8 +356,11 @@ public bool HasListeners()
/// </summary>
public void Dispose()
{
_listeners = null;
s_activeSources.Remove(this);
if (IsSupported)
{
_listeners = null;
s_activeSources.Remove(this);
}
}

/// <summary>
Expand All @@ -348,7 +371,7 @@ public static void AddActivityListener(ActivityListener listener)
{
ArgumentNullException.ThrowIfNull(listener);

if (s_allListeners.AddIfNotExist(listener))
if (IsSupported && s_allListeners.AddIfNotExist(listener))
{
s_activeSources.EnumWithAction((source, obj) => {
var shouldListenTo = ((ActivityListener)obj).ShouldListenTo;
Expand All @@ -364,6 +387,10 @@ public static void AddActivityListener(ActivityListener listener)

internal void AddListener(ActivityListener listener)
{
if (!IsSupported)
{
return;
}
if (_listeners == null)
{
Interlocked.CompareExchange(ref _listeners, new SynchronizedList<ActivityListener>(), null);
Expand All @@ -374,12 +401,20 @@ internal void AddListener(ActivityListener listener)

internal static void DetachListener(ActivityListener listener)
{
if (!IsSupported)
{
return;
}
s_allListeners.Remove(listener);
s_activeSources.EnumWithAction((source, obj) => source._listeners?.Remove((ActivityListener) obj), listener);
}

internal void NotifyActivityStart(Activity activity)
{
if (!IsSupported)
{
return;
}
Debug.Assert(activity != null);

// _listeners can get assigned to null in Dispose.
Expand All @@ -392,6 +427,10 @@ internal void NotifyActivityStart(Activity activity)

internal void NotifyActivityStop(Activity activity)
{
if (!IsSupported)
{
return;
}
Debug.Assert(activity != null);

// _listeners can get assigned to null in Dispose.
Expand All @@ -404,6 +443,10 @@ internal void NotifyActivityStop(Activity activity)

internal void NotifyActivityAddException(Activity activity, Exception exception, ref TagList tags)
{
if (!IsSupported)
{
return;
}
Debug.Assert(activity != null);

// _listeners can get assigned to null in Dispose.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Diagnostics.Metrics;
using System.Threading;

namespace System.Diagnostics
Expand Down Expand Up @@ -144,7 +145,10 @@ public DiagnosticListener(string name)

// Touch DiagnosticSourceEventSource.Logger so we ensure that the
// DiagnosticSourceEventSource has been constructed (and thus is responsive to ETW requests to be enabled).
GC.KeepAlive(DiagnosticSourceEventSource.Log);
if (Meter.IsEventSourceSupported)
{
GC.KeepAlive(DiagnosticSourceEventSource.Log);
}
}

/// <summary>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,11 @@ public static DsesActivitySourceListener Create(
DiagnosticSourceEventSource eventSource,
DsesFilterAndTransform activitySourceSpecs)
{
if (!ActivitySource.IsSupported)
{
throw new NotSupportedException("Linked away");
}

var listener = new DsesActivitySourceListener(eventSource);

listener.NormalizeActivitySourceSpecsList(activitySourceSpecs);
Expand Down
Loading