OpenTelemetry Tracing API for .NET
This document teaches how to use the OpenTelemetry .NET API. To learn how to install and configure the OpenTelemetry .NET SDK, see Getting started with OpenTelemetry .NET.
OpenTelemetry-DotNet
OpenTelemetry-DotNet is the .NET implementation of OpenTelemetry. It provides the OpenTelemetry Tracing API which you can use to instrument your application with traces.
Activity API
The OpenTelemetry API reuses the .NET Activity API, which existed long before OpenTelemetry was created. The Activity API covers all OpenTelemetry requirements but uses slightly different API and terminology.
OpenTelemetry API | .NET Activity API |
---|---|
Tracer | ActivitySource |
Span | Activity |
NoopSpan | null activity |
SpanContext | ActivityContext |
Span kind | ActivityKind |
Attribute | Tag |
SpanLink | ActivityLink |
SpanEvent | ActivityEvent |
span.IsRecording() | activity.IsAllDataRequested |
To install the Activity API, add the following dependency to your project:
<ItemGroup>
<PackageReference Include="System.Diagnostics.DiagnosticSource" Version="5.0.1" />
</ItemGroup>
Quickstart
Step 1: Start with Your Function
Let's instrument the following function:
public string RedisGet(string key) {
return this.redisDb.StringGet("mykey");
}
Step 2: Add ActivitySource and Create a Span
Wrap the operation with a span:
using System.Diagnostics;
var activitySource = new ActivitySource("app_or_lib_name");
public string RedisGet(string key) {
using var activity = this.activitySource.StartActivity("RedisGet");
return this.redisDb.StringGet("mykey");
}
Step 3: Handle Errors and Set Status
Record errors and set status code:
public string RedisGet(string key) {
using var activity = this.activitySource.StartActivity("RedisGet");
try {
return this.redisDb.StringGet("mykey");
} catch (Exception ex) {
activity?.RecordException(ex);
activity?.SetStatus(Status.Error.WithDescription(ex.Message));
throw; // Re-throw the exception
}
}
Step 4: Add Contextual Information
Record contextual information with attributes:
public string RedisGet(string key) {
using var activity = this.activitySource.StartActivity("RedisGet");
if (activity != null && activity.IsAllDataRequested) {
activity.SetTag("redis.key", key);
}
try {
return this.redisDb.StringGet("mykey");
} catch (Exception ex) {
activity?.RecordException(ex);
activity?.SetStatus(Status.Error.WithDescription(ex.Message));
throw;
}
}
And that's it! The operation is fully instrumented.
Creating a Tracer
To start creating spans, you need a tracer (ActivitySource
). You can create a tracer by providing the name and version of the library/application doing the instrumentation:
using System.Diagnostics;
static ActivitySource activitySource = new ActivitySource(
"app_or_package_name",
"semver1.0.0");
You can have as many tracers as you want, but usually you need only one tracer per application or library. Later, you can use tracer names to identify the instrumentation that produces the spans.
Creating Spans
You can create spans using StartActivity
. Because StartActivity
returns a null
activity when OpenTelemetry is not enabled or the span was not sampled, you need to check for null
when working with activities:
var activity = activitySource.StartActivity("operation-name", ActivityKind.Server);
// Perform your operation
// End the span when the operation we are measuring is done
activity?.Stop();
You can also create spans in using
blocks to automatically stop the activity at the end of the block:
using (var activity = activitySource.StartActivity("operation-name"))
{
activity?.SetTag("http.method", "GET");
} // Activity is automatically stopped during block disposal
Current Span
OpenTelemetry stores the active span in a context and saves the context in a pluggable context storage. You can nest contexts inside each other, and OpenTelemetry will automatically activate the parent span context when you end the span.
To get the active span from the current context:
// May be null if there is no active span
var activity = Activity.Current;
Adding Span Attributes
To record contextual information, you can annotate spans with attributes. For example, an HTTP endpoint may have attributes such as http.method = GET
and http.route = /projects/:id
.
// To avoid expensive computations, check that the span was sampled
// before setting any attributes
if (activity != null && activity.IsAllDataRequested)
{
activity.SetTag("http.method", "GET");
activity.SetTag("http.route", "/projects/:id");
}
You can name attributes as you want, but for common operations you should use the semantic attributes convention.
Adding Span Events
You can annotate spans with events. For example, you can use events to record log messages:
activity?.AddEvent(
new ActivityEvent(
"log",
DateTime.UtcNow,
new ActivityTagsCollection(
new Dictionary<string, object>
{
{ "log.severity", "error" },
{ "log.message", "User not found" },
{ "enduser.id", 123 },
}
)
)
);
Setting Status Code
You can set an error
status code to indicate that the operation contains an error:
catch (Exception ex)
{
activity?.SetStatus(Status.Error.WithDescription(ex.Message));
}
Recording Exceptions
OpenTelemetry provides a shortcut to record exceptions, which is usually used together with SetStatus
:
using (var activity = activitySource.StartActivity("operation-name"))
{
try
{
Func();
}
catch (Exception ex)
{
activity?.RecordException(ex);
activity?.SetStatus(Status.Error.WithDescription(ex.Message));
throw; // Re-throw if needed
}
}
OpenTelemetry APM
Uptrace is a OpenTelemetry backend that supports distributed tracing, metrics, and logs. You can use it to monitor applications and troubleshoot issues.
Uptrace comes with an intuitive query builder, rich dashboards, alerting rules with notifications, and integrations for most languages and frameworks.
Uptrace can process billions of spans and metrics on a single server and allows you to monitor your applications at 10x lower cost.
In just a few minutes, you can try Uptrace by visiting the cloud demo (no login required) or running it locally with Docker. The source code is available on GitHub.