Skip to content

Commit

Permalink
[Azure.Core Shared] Adding link to Diagnostic Scope should take attri…
Browse files Browse the repository at this point in the history
…butes (#10368)
  • Loading branch information
kinelski authored Mar 6, 2020
1 parent 4b30e37 commit 7ff0c31
Show file tree
Hide file tree
Showing 2 changed files with 45 additions and 1 deletion.
10 changes: 9 additions & 1 deletion sdk/core/Azure.Core/src/Shared/DiagnosticScope.cs
Original file line number Diff line number Diff line change
Expand Up @@ -49,14 +49,22 @@ public void AddAttribute<T>(string name, T value, Func<T, string> format)
}
}

public void AddLink(string id)
public void AddLink(string id, IDictionary<string, string>? attributes = null)
{
if (_activity != null)
{
var linkedActivity = new Activity("LinkedActivity");
linkedActivity.SetW3CFormat();
linkedActivity.SetParentId(id);

if (attributes != null)
{
foreach (var kvp in attributes)
{
linkedActivity.AddTag(kvp.Key, kvp.Value);
}
}

_activity.AddLink(linkedActivity);
}
}
Expand Down
36 changes: 36 additions & 0 deletions sdk/core/Azure.Core/tests/ClientDiagnosticsTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, string>()
{
{"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<Activity>)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()
{
Expand Down

0 comments on commit 7ff0c31

Please sign in to comment.