diff --git a/sdk/core/Azure.Core/src/Shared/DiagnosticScope.cs b/sdk/core/Azure.Core/src/Shared/DiagnosticScope.cs index 3914f932a314..1ce15369ad70 100644 --- a/sdk/core/Azure.Core/src/Shared/DiagnosticScope.cs +++ b/sdk/core/Azure.Core/src/Shared/DiagnosticScope.cs @@ -49,7 +49,7 @@ public void AddAttribute(string name, T value, Func format) } } - public void AddLink(string id) + public void AddLink(string id, IDictionary? attributes = null) { if (_activity != null) { @@ -57,6 +57,14 @@ public void AddLink(string id) linkedActivity.SetW3CFormat(); linkedActivity.SetParentId(id); + if (attributes != null) + { + foreach (var kvp in attributes) + { + linkedActivity.AddTag(kvp.Key, kvp.Value); + } + } + _activity.AddLink(linkedActivity); } } diff --git a/sdk/core/Azure.Core/tests/ClientDiagnosticsTests.cs b/sdk/core/Azure.Core/tests/ClientDiagnosticsTests.cs index 4a74d46da2de..52d74d5ab9eb 100644 --- a/sdk/core/Azure.Core/tests/ClientDiagnosticsTests.cs +++ b/sdk/core/Azure.Core/tests/ClientDiagnosticsTests.cs @@ -116,6 +116,42 @@ public void AddLinkCallsPassesLinksAsPartOfStartPayload() Assert.AreEqual(0, testListener.Events.Count); } + [Test] + public void AddLinkCreatesLinkedActivityWithTags() + { + using var testListener = new TestDiagnosticListener("Azure.Clients"); + DiagnosticScopeFactory clientDiagnostics = new DiagnosticScopeFactory("Azure.Clients", "Microsoft.Azure.Core.Cool.Tests", true); + + DiagnosticScope scope = clientDiagnostics.CreateScope("ActivityName"); + + var expectedTags = new Dictionary() + { + {"key1", "value1"}, + {"key2", "value2"} + }; + + scope.AddLink("id", expectedTags); + scope.Start(); + + (string Key, object Value, DiagnosticListener) startEvent = testListener.Events.Dequeue(); + + scope.Dispose(); + + (string Key, object Value, DiagnosticListener) stopEvent = testListener.Events.Dequeue(); + + Assert.Null(Activity.Current); + Assert.AreEqual("ActivityName.Start", startEvent.Key); + Assert.AreEqual("ActivityName.Stop", stopEvent.Key); + + var activities = (IEnumerable)startEvent.Value.GetType().GetProperty("Links").GetValue(startEvent.Value); + Activity linkedActivity = activities.Single(); + + Assert.AreEqual(ActivityIdFormat.W3C, linkedActivity.IdFormat); + Assert.AreEqual("id", linkedActivity.ParentId); + + CollectionAssert.AreEquivalent(expectedTags, linkedActivity.Tags); + } + [Test] public void FailedStopsActivityAndWritesExceptionEvent() {