C# Reference ยท Exceptions and Diagnostics
Activity and ActivitySource
Reference for System.Diagnostics.Activity and ActivitySource: start spans, add tags and events, nest activities and listen with ActivityListener.
System.Diagnostics.Activity is .NET's representation of a span in distributed tracing: a named, timed unit of work with an id, a parent, tags (key/value data) and events. An ActivitySource is the factory that your code or library owns; it creates activities and costs almost nothing when nobody listens.
Activities only exist when something has subscribed. ActivitySource.StartActivity returns null when there is no listener, so you always use ?. on the result. In a real service OpenTelemetry (or Application Insights) registers the listener and exports the spans; in a small program you can register an ActivityListener yourself, as the examples do.
static readonly ActivitySource Source = new("MyCompany.Orders"); using Activity? activity = Source.StartActivity("PlaceOrder"); activity?.SetTag("order.id", 4711);
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.
Syntax
public sealed class ActivitySource : IDisposable { public ActivitySource(string name, string? version = ""); public Activity? StartActivity(string name = "", ActivityKind kind = ActivityKind.Internal); public Activity? StartActivity(string name, ActivityKind kind, ActivityContext parentContext, IEnumerable<KeyValuePair<string, object?>>? tags = null, IEnumerable<ActivityLink>? links = null, DateTimeOffset startTime = default); public bool HasListeners(); }
| Member | Description |
|---|---|
Activity.Current |
The ambient activity of the current async flow (stored in an AsyncLocal). |
SetTag(key, value) |
Adds or replaces a tag. Returns the activity so calls can be chained. |
AddEvent(ActivityEvent) |
Records a point-in-time event inside the span. |
SetStatus(code, description) |
Marks the span Ok or Error. |
ActivityKind |
Internal, Server, Client, Producer, Consumer. |
TraceId, SpanId, ParentId |
W3C ids (32 and 16 hex characters). They are random, so do not print them in tests. |
Dispose() / Stop() |
Ends the span and restores the previous Activity.Current. |
Returns: StartActivity returns an Activity?, null if no listener wants data from the source.
Errors: none in normal use. A listener that throws in its callbacks can break the code that starts or stops the activity, so keep callbacks short and safe.
Usage notes
- Always use
?.on the result ofStartActivity. Branching onnullis also the cheap way to skip expensive tag computations. - Create one
static readonly ActivitySourceper library or component, named like the namespace. Dispose it only when the application shuts down. - Parenting is automatic. A new activity becomes a child of
Activity.Current, and disposing it restores the parent. This followsawaitbecauseCurrentis async-local. - Wrap activities in
usingso they always stop, also when an exception is thrown. An activity that is never stopped never reaches the exporter. - Tag names should follow the OpenTelemetry semantic conventions where one exists (
http.request.method,db.system). Tag values should be low-cardinality for metrics, but spans may carry ids. - Sampling decides cost.
AllDatarecords tags;PropagationDatacreates only ids;Nonereturnsnull. Production systems usually sample a percentage. - ASP.NET Core and
HttpClientalready create activities, so your spans nest under theirs without extra work. - Reading data back: listeners get
ActivityStartedandActivityStoppedcallbacks.Durationis only valid after the stop, and it is a clock value, so avoid printing it.
Related
- Metrics, Logging,
DebugandTrace - Lessons: Debugging and diagnostics, Logging