System.Diagnostics.ActivitySource.StartActivity returns null
Asked Answered
B

2

12

I haven't find the way to make activitySource.StartActivity return non-null activity, which is different comparing to DiagnosticSource.StartActivity behavior. Is it expected? Am I'missing something obvious?

I can see docs says: "The created activity object, if it had active listeners, or null if it has no event listeners." The following test still fails, what's the correct way of initializing ActivityListener? The package I'm using is "System.Diagnostics.DiagnosticSource" Version="5.0.0".

    [TestMethod]
    public void Start_Not_Null_When_ActivityListener_Added_And_ShouldListenTo_Explicitly_Defined_Activity()
    {
        var activitySource = new ActivitySource("ActivitySourceName");
        var activityListener = new ActivityListener
        {
            ShouldListenTo = s => true
        };
        ActivitySource.AddActivityListener(activityListener);
        
        using var activity = activitySource.StartActivity($"MethodType:/Path");
        
        Assert.IsNotNull(activity);
    }
Bores answered 22/11, 2020 at 16:7 Comment(0)
B
15

This test pass with the help from github:

[TestMethod]
public void Start_Not_Null_When_ActivityListener_Added_And_ShouldListenTo_Explicitly_Defined_Activity()
{
    var activitySource = new ActivitySource("ActivitySourceName");
    var activityListener = new ActivityListener
    {
        ShouldListenTo = s => true,
        SampleUsingParentId = (ref ActivityCreationOptions<string> activityOptions) => ActivitySamplingResult.AllData,
        Sample = (ref ActivityCreationOptions<ActivityContext> activityOptions) => ActivitySamplingResult.AllData
    };
    ActivitySource.AddActivityListener(activityListener);

    using var activity = activitySource.StartActivity("MethodType:/Path");

    Assert.IsNotNull(activity);
}
Bores answered 22/11, 2020 at 16:11 Comment(0)
S
5

The answer to this is you need to include a ActivitySamplingResult that's not set to None. The default appears to be none. MaGu's answer works because they set:

Sample = (ref ActivityCreationOptions<ActivityContext> activityOptions) => ActivitySamplingResult.AllData

The documentation for the method around StartActivity says it needs a listener but this is not the complete story you need an active listener that will do something with the activity. Setting the sample to None means it's effectively not in

Semivitreous answered 19/6, 2022 at 3:3 Comment(1)
Thanks for this tip. SetSampler(new AlwaysOnSampler()) worked for me. However I think @Bores 's answer is the more long term solution. Either way, +1 from me for this answerTelluric

© 2022 - 2024 — McMap. All rights reserved.