OpenTelemetry.Api
1.10.0
Prefix Reserved
dotnet add package OpenTelemetry.Api --version 1.10.0
NuGet\Install-Package OpenTelemetry.Api -Version 1.10.0
<PackageReference Include="OpenTelemetry.Api" Version="1.10.0" />
paket add OpenTelemetry.Api --version 1.10.0
#r "nuget: OpenTelemetry.Api, 1.10.0"
// Install OpenTelemetry.Api as a Cake Addin #addin nuget:?package=OpenTelemetry.Api&version=1.10.0 // Install OpenTelemetry.Api as a Cake Tool #tool nuget:?package=OpenTelemetry.Api&version=1.10.0
OpenTelemetry .NET API
- Installation
- Introduction
- Introduction to OpenTelemetry .NET Tracing API
- Instrumenting a library/application with .NET Activity API
- Instrumenting a library/application with OpenTelemetry.API Shim
- Troubleshooting
- References
Installation
dotnet add package OpenTelemetry.Api
Introduction
Application developers and library authors use OpenTelemetry API to instrument their application/library. The API only surfaces necessary abstractions to instrument an application/library. It does not address concerns like how telemetry is exported to a specific telemetry backend, how to sample the telemetry, etc. The API consists of Tracing API, Logging API, Metrics API, Context and Propagation API, and a set of semantic conventions.
Tracing API
Tracing API allows users to generate Spans, which represent a single operation within a trace. Spans can be nested to form a trace tree. Each trace contains a root span, which typically describes the entire operation and, optionally one or more child-spans for its child-operations.
Logging API
OpenTelemetry .NET does not introduce its own API for logging. Instead it provides an integration with the well known Microsoft.Extensions.Logging API.
Metrics API
Metrics API allows users to capture measurements about the execution of a computer program at runtime. The Metrics API is designed to process raw measurements, generally with the intent to produce continuous summaries of those measurements.
Baggage API
Baggage API allows users to add context to metric, traces, and logs. Baggage can be propagated out of proc using Propagators. OpenTelemetry SDK ships a BaggagePropagator and enables it by default.
It is important to note that Baggage
is not automatically attached to any
telemetry. User can explicitly read Baggage
and use it to enrich metrics,
logs and traces. An example of doing this for traces is shown
here.
// Use GetBaggage to get all the key/value pairs present in Baggage
foreach (var item in Baggage.GetBaggage())
{
Console.WriteLine(item.Key);
Console.WriteLine(item.Value);
}
// Use SetBaggage method to add a key/value pair in Baggage
Baggage.SetBaggage("AppName", "MyApp");
Baggage.SetBaggage("Region", "West US");
// Use RemoveBaggage method to remove a key/value pair in Baggage
Baggage.RemoveBaggage("AppName");
// Use ClearBaggage method to remove all the key/value pairs in Baggage
Baggage.ClearBaggage();
The recommended way to add Baggage is to use the Baggage.SetBaggage()
API.
OpenTelemetry users should not use the Activity.AddBaggage
method.
Introduction to OpenTelemetry .NET Tracing API
.NET runtime had Activity
class for a long time, which was meant to be used
for tracing purposes and represents the equivalent of the OpenTelemetry
Span.
OpenTelemetry .NET is reusing the existing Activity
and associated classes to
represent the OpenTelemetry Span
. This means, users can instrument their
applications/libraries to emit OpenTelemetry compatible traces by using just the
.NET Runtime.
The Activity
and associated classes are shipped as part of
System.Diagnostics.DiagnosticSource
nuget package. Version 5.0.0 of this
package contains improvements to Activity
class which makes it more closely
aligned with OpenTelemetry API
specification.
Even though Activity
enables all the scenarios OpenTelemetry supports, users
who are already familiar with OpenTelemetry terminology may find it easy to
operate with that terminology. For instance, StartSpan
may be preferred over
StartActivity
. To help with this transition, the OpenTelemetry.API package has
shim classes to wrap around the
.NET Activity
classes.
The shim exist only in the API. OpenTelemetry SDK for .NET will be operating
entirely with Activity
only. Irrespective of whether shim classes or
Activity
is used for instrumentation, the end result would be same. i.e
Processors/Exporters see the same data.
The recommended way of instrumenting is by using the .NET Activity API. Users are required to just take dependency on the DiagnosticSource. Adding dependency to OpenTelemetry.API is required only for the following scenarios:
You want to use terminology matching OpenTelemetry spec (Span vs Activity). The shim can be useful for such users. Refer to the comparison of Activity API and OpenTelemetry Tracing API if you want to compare the differences.
Your library performs communication with other libraries/components, and want to access Propagators, to inject and extract context data. Some of the most common libraries requiring this include HttpClient, ASP.NET Core. This or contrib repository already provides instrumentation for these common libraries. If your library is not built on top of these, and want to leverage propagators, follow the Context propagation section.
You want to leverage Baggage API.
Instrumenting a library/application with .NET Activity API
Basic usage
As mentioned in the introduction, the instrumentation API for OpenTelemetry .NET
is the .NET Activity
API. Guidance for instrumenting using this API is
documented fully in the TBD(dotnet activity user guide link), but is described
here as well.
Install the latest stable
System.Diagnostics.DiagnosticSource
to your application or library.dotnet add package System.Diagnostics.DiagnosticSource
Create an
ActivitySource
, providing the name and version of the library/application doing the instrumentation.ActivitySource
instance is typically created once and is reused throughout the application/library.static ActivitySource activitySource = new ActivitySource( "MyCompany.MyProduct.MyLibrary", "1.0.0");
The above requires import of the
System.Diagnostics
namespace.Use the
ActivitySource
instance from above to createActivity
instances, which represent a single operation within a trace. The parameter passed is theDisplayName
of the activity.var activity = activitySource.StartActivity("ActivityName");
If there are no listeners interested in this activity, the activity above will be null. This happens when the final application does not enable OpenTelemetry (or other
ActivityListener
s), or when OpenTelemetry samplers chose not to sample this activity. Ensure that all subsequent calls using this activity are protected with a null check.Populate activity with tags following the OpenTelemetry semantic conventions, using the SetTag API. It is highly recommended to check
activity.IsAllDataRequested
, before populating any tags which are not readily available.IsAllDataRequested
is the same as Span.IsRecording and will be false when samplers decide to not record the activity, and this can be used to avoid any expensive operation to retrieve tags.activity?.SetTag("http.method", "GET"); if (activity != null && activity.IsAllDataRequested == true) { activity.SetTag("http.url", "http://www.mywebsite.com"); }
Perform application/library logic.
Stop the activity when done.
activity?.Stop();
Alternately, as
Activity
implementsIDisposable
, it can be used with ausing
block, which ensures activity gets stopped upon disposal. This is shown below.using (var activity = activitySource.StartActivity("ActivityName") { activity?.SetTag("http.method", "GET"); } // Activity gets stopped automatically at end of this block during dispose.
The above showed the basic usage of instrumenting using Activity
. The
following sections describes more features.
Activity creation options
Basic usage example above showed how StartActivity
method can be used to start
an Activity
. The started activity will automatically becomes the Current
activity. It is important to note that the StartActivity
returns null
, if no
listeners are interested in the activity to be created. This happens when the
final application does not enable OpenTelemetry, or when OpenTelemetry samplers
chose not to sample this activity.
StartActivity
has many overloads to control the activity creation.
ActivityKind
Activity
has a property calledActivityKind
which represents OpenTelemetry SpanKind. The default value will beInternal
.StartActivity
allows passing theActivityKind
while starting anActivity
.var activity = activitySource.StartActivity("ActivityName", ActivityKind.Server);
Parent using
ActivityContext
ActivityContext
represents the OpenTelemetry SpanContext. While starting a newActivity
, the currently activeActivity
is automatically taken as the parent of the new activity being created.StartActivity
allows passing explicitActivityContext
to override this behavior.var parentContext = new ActivityContext( ActivityTraceId.CreateFromString("0af7651916cd43dd8448eb211c80319c"), ActivitySpanId.CreateFromString("b7ad6b7169203331"), ActivityTraceFlags.None); var activity = activitySource.StartActivity( "ActivityName", ActivityKind.Server, parentContext);
As
ActivityContext
follows the W3C Trace-Context, it is also possible to provide the parent context as a single string matching thetraceparent
header of the W3C Trace-Context. This is shown below.var activity = activitySource.StartActivity( "ActivityName", ActivityKind.Server, "00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01");
Initial Tags
Tags
inActivity
represents the OpenTelemetry Span Attributes. Earlier sample showed the usage ofSetTag
method ofActivity
to add tags. Refer to the specification for best practices on naming tags. It is also possible to provide an initial set of tags during activity creation, as shown below. It is recommended to provide all availableTags
during activity creation itself, as Samplers can only consider information present during activity creation time.var initialTags = new ActivityTagsCollection(); initialTags["com.mycompany.product.mytag1"] = "tagValue1"; initialTags["com.mycompany.product.mytag2"] = "tagValue2"; var activity = activitySource.StartActivity( "ActivityName", ActivityKind.Server, "00-0af7651916cd43dd8448eb211c80319c-b7ad6b7169203331-01", initialTags);
The above requires import of the
System.Collections.Generic
namespace.Activity Links
Apart from the parent-child relation, activities can be linked using
ActivityLinks
which represent the OpenTelemetry Links. The linked activities must be provided during the creation time, as shown below.var activityLinks = new List<ActivityLink>(); var linkedContext1 = new ActivityContext( ActivityTraceId.CreateFromString("0af7651916cd43dd8448eb211c80319c"), ActivitySpanId.CreateFromString("b7ad6b7169203331"), ActivityTraceFlags.None); var linkedContext2 = new ActivityContext( ActivityTraceId.CreateFromString("4bf92f3577b34da6a3ce929d0e0e4736"), ActivitySpanId.CreateFromString("00f067aa0ba902b7"), ActivityTraceFlags.Recorded); activityLinks.Add(new ActivityLink(linkedContext1)); activityLinks.Add(new ActivityLink(linkedContext2)); var activity = activitySource.StartActivity( "ActivityWithLinks", ActivityKind.Server, default(ActivityContext), initialTags, activityLinks);
Note that
Activity
above is created withdefault(ActivityContext)
parent, which makes it child of implicitActivity.Current
or orphan if there is noCurrent
.
Adding Events
It is possible to add
events
to Activity
using the AddEvent
method as shown below.
activity?.AddEvent(new ActivityEvent("sample activity event."));
Apart from providing name, timestamp and attributes can be provided by using
corresponding overloads of ActivityEvent
.
Setting Status
OpenTelemetry defines a concept called
Status
to be associated with Activity
. Starting with DiagnosticSource
6.0,
SetStatus
API on Activity
can be used to set the status and description as
shown below:
activity?.SetStatus(ActivityStatusCode.Ok);
activity?.SetStatus(ActivityStatusCode.Error, "Error Description");
All the official Exporters shipped from this repo support the above shown mechanism of setting status.
Setting Status - DiagnosticSource version older than 6.0
Prior to DiagnosticSource
6.0
there was no Status
field in Activity
, and hence Status
is set to an
Activity
using the following special tags:
otel.status_code
is the Tag
name used to store the StatusCode
, and
otel.status_description
is the Tag
name used to store the optional
Description
.
Example:
activity?.SetTag("otel.status_code", "ERROR");
activity?.SetTag("otel.status_description", "error status description");
Values for the StatusCode tag must be one of the strings "UNSET", "OK", or
"ERROR", which correspond respectively to the enums Unset
, Ok
, and Error
from StatusCode
.
If using OpenTelemetry API shim,
then you can leverage the SetStatus
extension method on Activity
as well.
Instrumenting using OpenTelemetry.API Shim
As mentioned in the introduction section, using OpenTelemetry.API Shim is only recommended if you want to use OpenTelemetry terminology like Tracer, Span instead of ActivitySource, Activity.
Follow this code for example usage of this shim.
Context propagation
OpenTelemetry.API must be used to access Propagators API which defines how to extract and inject context across process boundaries. This is typically required if you are not using any of the .NET communication libraries which has instrumentations already available which does the propagation (eg: Asp.Net Core or HttpClient). In such cases, context extraction and propagation is the responsibility of the library itself. An example would be a producer-consumer pattern using some queuing library like RabbitMQ. Follow the messaging example for examples on how to inject and extract context.
[!NOTE] If you are using the instrumentation libraries shipped from this repo [e.g. ASP.NET Core or HttpClient], context propagation is done by using the default propagator. The default can be updated by calling
Sdk.SetDefaultTextMapPropagator
and passing the propagator of your choice.
Propagator Api used by the instrumentation libraries is different than
DistributedContextPropagator
available in System.Diagnostics
. Implementing this will have no impact on the
propagation, if used alongside instrumentation libraries.
Introduction to OpenTelemetry .NET Metrics API
Metrics in OpenTelemetry .NET are a somewhat unique implementation of the
OpenTelemetry project, as the Metrics API is incorporated directly into the .NET
runtime itself, as part of the
System.Diagnostics.DiagnosticSource
package. This means, users can instrument their applications/libraries to emit
metrics by simply using the System.Diagnostics.DiagnosticSource
package. This
package can be used in applications targeting any of the officially supported
versions of .NET and .NET
Framework (an older
Windows-based .NET implementation).
Instrumenting a library/application with .NET Metrics API
Basic metric usage
Install the latest stable version of
System.Diagnostics.DiagnosticSource
to your application or library.dotnet add package System.Diagnostics.DiagnosticSource
Create a
Meter
, providing the name and version of the library/application doing the instrumentation. TheMeter
instance is typically created once and is reused throughout the application/library.static Meter meter = new Meter( "companyname.product.instrumentationlibrary", "1.0.0");
The above requires import of the
System.Diagnostics.Metrics
namespace.[!NOTE] It is important to note that
Meter
instances are created by using its constructor, and not by calling aGetMeter
method on theMeterProvider
. This is an important distinction from the OpenTelemetry specification, whereMeter
s are obtained fromMeterProvider
.Use the
Meter
instance from above to create instruments, which can be used to report measurements. Just like meter instances, the instrument instances are to be created once and reused throughout the application/library.static Counter<long> MyFruitCounter = meter.CreateCounter<long>("MyFruitCounter");
Use the instruments to report measurements, along with the attributes.
MyFruitCounter.Add(1, new("name", "apple"), new("color", "red"));
The above showed the usage of a Counter
instrument. The following sections
describes more kinds of instruments.
Instrument types
See this.
Troubleshooting
This component uses an EventSource with the name "OpenTelemetry-Api" for its internal logging. Please refer to SDK troubleshooting for instructions on seeing these internal logs.
References
Product | Versions Compatible and additional computed target framework versions. |
---|---|
.NET | net5.0 was computed. net5.0-windows was computed. net6.0 was computed. net6.0-android was computed. net6.0-ios was computed. net6.0-maccatalyst was computed. net6.0-macos was computed. net6.0-tvos was computed. net6.0-windows was computed. net7.0 was computed. net7.0-android was computed. net7.0-ios was computed. net7.0-maccatalyst was computed. net7.0-macos was computed. net7.0-tvos was computed. net7.0-windows was computed. net8.0 is compatible. net8.0-android was computed. net8.0-browser was computed. net8.0-ios was computed. net8.0-maccatalyst was computed. net8.0-macos was computed. net8.0-tvos was computed. net8.0-windows was computed. net9.0 is compatible. |
.NET Core | netcoreapp2.0 was computed. netcoreapp2.1 was computed. netcoreapp2.2 was computed. netcoreapp3.0 was computed. netcoreapp3.1 was computed. |
.NET Standard | netstandard2.0 is compatible. netstandard2.1 was computed. |
.NET Framework | net461 was computed. net462 is compatible. net463 was computed. net47 was computed. net471 was computed. net472 was computed. net48 was computed. net481 was computed. |
MonoAndroid | monoandroid was computed. |
MonoMac | monomac was computed. |
MonoTouch | monotouch was computed. |
Tizen | tizen40 was computed. tizen60 was computed. |
Xamarin.iOS | xamarinios was computed. |
Xamarin.Mac | xamarinmac was computed. |
Xamarin.TVOS | xamarintvos was computed. |
Xamarin.WatchOS | xamarinwatchos was computed. |
-
.NETFramework 4.6.2
- System.Diagnostics.DiagnosticSource (>= 9.0.0)
-
.NETStandard 2.0
- System.Diagnostics.DiagnosticSource (>= 9.0.0)
-
net8.0
- System.Diagnostics.DiagnosticSource (>= 9.0.0)
-
net9.0
- System.Diagnostics.DiagnosticSource (>= 9.0.0)
NuGet packages (178)
Showing the top 5 NuGet packages that depend on OpenTelemetry.Api:
Package | Downloads |
---|---|
OpenTelemetry.Api.ProviderBuilderExtensions
Contains extensions to register OpenTelemetry in applications using Microsoft.Extensions.DependencyInjection |
|
OpenTelemetry.Instrumentation.Runtime
dotnet runtime instrumentation for OpenTelemetry .NET |
|
Npgsql.OpenTelemetry
Package Description |
|
OpenTelemetry.Instrumentation.Process
dotnet process instrumentation for OpenTelemetry .NET |
|
Marten
.NET Transactional Document DB and Event Store on PostgreSQL |
GitHub repositories (27)
Showing the top 5 popular GitHub repositories that depend on OpenTelemetry.Api:
Repository | Stars |
---|---|
danielgerlag/workflow-core
Lightweight workflow engine for .NET Standard
|
|
ChilliCream/graphql-platform
Welcome to the home of the Hot Chocolate GraphQL server for .NET, the Strawberry Shake GraphQL client for .NET and Banana Cake Pop the awesome Monaco based GraphQL IDE.
|
|
npgsql/npgsql
Npgsql is the .NET data provider for PostgreSQL.
|
|
open-telemetry/opentelemetry-dotnet
The OpenTelemetry .NET Client
|
|
JasperFx/marten
.NET Transactional Document DB and Event Store on PostgreSQL
|
Version | Downloads | Last updated | |
---|---|---|---|
1.10.0 | 143,108 | 11/12/2024 | |
1.10.0-rc.1 | 6,677 | 11/1/2024 | |
1.10.0-beta.1 | 23,492 | 9/30/2024 | |
1.9.0 | 13,673,191 | 6/14/2024 | |
1.9.0-rc.1 | 140,628 | 6/7/2024 | |
1.9.0-alpha.1 | 58,709 | 5/20/2024 | |
1.8.1 | 9,909,220 | 4/18/2024 | |
1.8.0 | 12,957,888 | 4/3/2024 | |
1.8.0-rc.1 | 774,069 | 3/27/2024 | |
1.8.0-beta.1 | 117,712 | 3/14/2024 | |
1.7.0 | 13,600,907 | 12/9/2023 | |
1.7.0-rc.1 | 1,455,456 | 11/30/2023 | |
1.7.0-alpha.1 | 500,652 | 10/17/2023 | |
1.6.0 | 17,924,918 | 9/6/2023 | |
1.6.0-rc.1 | 1,465,170 | 8/21/2023 | |
1.6.0-alpha.1 | 427,707 | 7/12/2023 | |
1.5.1 | 14,762,674 | 6/26/2023 | |
1.5.0 | 9,472,022 | 6/6/2023 | |
1.5.0-rc.1 | 1,815,051 | 5/26/2023 | |
1.5.0-alpha.2 | 1,048,343 | 4/1/2023 | |
1.5.0-alpha.1 | 1,284,298 | 3/8/2023 | |
1.4.0 | 16,049,906 | 2/24/2023 | |
1.4.0-rc.4 | 2,756,574 | 2/11/2023 | |
1.4.0-rc.3 | 745,075 | 2/2/2023 | |
1.4.0-rc.2 | 1,106,246 | 1/9/2023 | |
1.4.0-rc.1 | 1,366,661 | 12/12/2022 | |
1.4.0-beta.3 | 2,210,617 | 11/7/2022 | |
1.4.0-beta.2 | 1,112,763 | 10/17/2022 | |
1.4.0-beta.1 | 425,555 | 9/30/2022 | |
1.4.0-alpha.2 | 1,795,702 | 8/18/2022 | |
1.4.0-alpha.1 | 1,367,117 | 8/3/2022 | |
1.3.2 | 4,499,582 | 12/20/2022 | |
1.3.1 | 11,983,744 | 9/8/2022 | |
1.3.0 | 12,047,993 | 6/3/2022 | |
1.3.0-rc.2 | 1,474,646 | 6/1/2022 | |
1.3.0-beta.2 | 218,147 | 5/17/2022 | |
1.3.0-beta.1 | 2,618,792 | 4/20/2022 | |
1.2.0 | 5,420,661 | 4/15/2022 | |
1.2.0-rc5 | 662,793 | 4/13/2022 | |
1.2.0-rc4 | 896,122 | 3/30/2022 | |
1.2.0-rc3 | 1,331,250 | 3/5/2022 | |
1.2.0-rc2 | 3,154,917 | 2/3/2022 | |
1.2.0-rc1 | 2,507,321 | 11/30/2021 | |
1.2.0-beta2.1 | 273,985 | 11/19/2021 | |
1.2.0-beta1 | 4,712,881 | 10/8/2021 | |
1.2.0-alpha4 | 63,582 | 9/23/2021 | |
1.2.0-alpha3 | 20,521 | 9/14/2021 | |
1.2.0-alpha2 | 91,263 | 8/25/2021 | |
1.2.0-alpha1 | 123,558 | 7/23/2021 | |
1.1.0 | 18,055,685 | 7/13/2021 | |
1.1.0-rc1 | 349,347 | 6/26/2021 | |
1.1.0-beta4 | 2,228,348 | 6/9/2021 | |
1.1.0-beta3 | 225,584 | 5/12/2021 | |
1.1.0-beta2 | 529,461 | 4/23/2021 | |
1.1.0-beta1 | 1,903,453 | 3/19/2021 | |
1.0.1 | 11,834,773 | 2/10/2021 | |
1.0.0-rc4 | 43,796 | 2/9/2021 | |
1.0.0-rc3 | 32,983 | 2/5/2021 | |
1.0.0-rc2 | 395,990 | 1/30/2021 | |
1.0.0-rc1.1 | 640,307 | 11/18/2020 | |
0.8.0-beta.1 | 125,723 | 11/5/2020 | |
0.7.0-beta.1 | 26,829 | 10/16/2020 | |
0.6.0-beta.1 | 220,014 | 9/16/2020 | |
0.5.0-beta.2 | 18,890 | 8/28/2020 | |
0.4.0-beta.2 | 142,637 | 7/25/2020 | |
0.3.0-beta.1 | 3,255 | 7/23/2020 | |
0.2.0-alpha.275 | 244,096 | 5/19/2020 | |
0.2.0-alpha.220 | 414,808 | 5/19/2020 | |
0.2.0-alpha.179 | 171,725 | 1/28/2020 | |
0.2.0-alpha.100 | 248,931 | 11/5/2019 |
For highlights and announcements see: https://github.com/open-telemetry/opentelemetry-dotnet/blob/core-1.10.0/RELEASENOTES.md.
For detailed changes see: https://github.com/open-telemetry/opentelemetry-dotnet/blob/core-1.10.0/src/OpenTelemetry.Api/CHANGELOG.md.