Skip to content

Instantly share code, notes, and snippets.

@itn3000
Last active November 6, 2020 09:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save itn3000/71d09bc2cb50f202c0a066d552315f6b to your computer and use it in GitHub Desktop.
Save itn3000/71d09bc2cb50f202c0a066d552315f6b to your computer and use it in GitHub Desktop.
ActivitySource sample
using System;
using System.Diagnostics;
namespace activitysample
{
class Program
{
private static readonly ActivitySource _ActivitySource = new ActivitySource("actsrc1");
static void Main(string[] args)
{
var listener = new ActivityListener();
listener.ActivityStarted += (Activity act) =>
{
// invoked when activity started
Console.WriteLine($"activity started: {act.OperationName}");
};
listener.ActivityStopped += (Activity act) =>
{
// invoked when activity stopped
Console.WriteLine($"activity stoppped: {act.OperationName}");
};
listener.ShouldListenTo += (ActivitySource actsrc) =>
{
// invoked when listening started and added new ActivitySource instance.
// if returned true, then begin to watch the ActivitySource events.
Console.WriteLine($"shouldlistento: {actsrc.Name}");
return actsrc.Name == "actsrc1";
};
listener.Sample = (ref ActivityCreationOptions<ActivityContext> options) =>
{
// invoked when before activity starting.
// if ActivitySamplingResult.None returned, no activity enabled.
// if ActivitySamplingResult.PropagationData returned, activity will be enabled and both IsAllDataRequested and Recorded flags will be false.
// if ActivitySamplingResult.AllData returned, activity will be enabled and IsAllDataRequested will be true, Recorded will be false.
// if ActivitySamplingResult.AllDataAndRecorded returned, activity will be enabled and IsAllDataRequested will be true, Recorded will be true.
Console.WriteLine($"sampling: {options.Name}");
return ActivitySamplingResult.AllDataAndRecorded;
};
ActivitySource.AddActivityListener(listener);
using (var act1 = _ActivitySource.StartActivity("act1", ActivityKind.Internal))
{
}
using (var act2 = _ActivitySource.StartActivity("act2", ActivityKind.Internal))
{
// child Activity, set act2 as parent Activity
using (var act3 = _ActivitySource.StartActivity("act2.child", ActivityKind.Internal))
{
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment