Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

System.Diagnostics.ActivitySource.StartActivity returns null

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);
    }
like image 797
MaGu Avatar asked Feb 19 '26 22:02

MaGu


2 Answers

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);
}
like image 163
MaGu Avatar answered Feb 22 '26 11:02

MaGu


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

like image 28
dxk3355 Avatar answered Feb 22 '26 11:02

dxk3355