Skip to main content

How to Trace Azure SDK Calls with OpenTelemetry in .NET C#

· 12 min read
Jagdish Kumawat
Founder @ Dewiride

Azure SDK libraries for .NET create OpenTelemetry spans for their own calls, and one line, AddSource("Azure.*"), collects them all. Here a small console app asks AzureCliCredential for two tokens, and both calls show up in the Aspire Dashboard with how long they took. The Azure.Experimental.EnableActivitySource switch wasn't needed.

OpenTelemetry is the open standard for traces, metrics and logs. A trace follows one operation, and it's made of spans: each span is one timed piece of work, with a name, a duration and attributes. In .NET, Microsoft's documentation explains, 'ActivitySource' is the implementation of Tracer and Activity is the implementation of 'Span'. Code creates spans through an ActivitySource that has a name, and an app collects them by naming the sources it wants with AddSource.

Azure SDK libraries are built on Azure.Core, which provides shared primitives, abstractions, and helpers for modern .NET Azure SDK client libraries, tracing included. Each client has its own source, named after the library and the client, so one pattern covers them all.

Syntax​

Syntax
using TracerProvider tracerProvider = Sdk.CreateTracerProviderBuilder()
.ConfigureResource(resource => resource.AddService("<service-name>"))
.AddSource("<source-name-pattern>")
.AddOtlpExporter()
.Build();
PartWhat it is
Sdk.CreateTracerProviderBuilder()Starts a tracer provider, the part of OpenTelemetry that collects spans and hands them to exporters
<service-name>Your app's name. It becomes the service.name attribute, and the dashboard lists the app under it
<source-name-pattern>The sources to listen to. Azure.* means every source whose name starts with Azure.; a narrower pattern such as Azure.Storage.Blobs.* takes only those clients
AddOtlpExporter()Sends the spans over OTLP, the OpenTelemetry protocol. With no options, it uses gRPC and sends to localhost:4317
usingDisposes the provider when the program ends, which flushes the spans it still holds

AddSource takes exact names or patterns. Its reference says Source names support wildcard matching, where * matches zero or more characters. The Azure SDK's diagnostics guide: By calling into AddSource("Azure.*") we're telling OpenTelemetry SDK to listen to all sources which name starts with Azure. And OpenTelemetry's guidance on the using: If you forget to dispose the TracerProvider instance before the application ends, activities might get dropped due to the lack of proper flush.

The Example​

A console app called TokenCheck asks AzureCliCredential for a token for Azure Resource Manager twice, one call after the other, and prints only each token's length. AzureCliCredential is the credential that signs in with your Azure CLI account. The spans go to the Aspire Dashboard, a local viewer for OpenTelemetry data.

Prerequisites​

  • The .NET 10 SDK. dotnet --version prints a version that starts with 10.0.
  • The Azure CLI, signed in with az login. The example's credential uses that sign-in.
  • The Aspire Dashboard, running on your computer. It receives OTLP at http://localhost:4317 and shows its pages at http://localhost:18888, the ports it uses by default.

Step 1: Create a Console App and Add the Packages​

Terminal
dotnet new console -n TokenCheck
cd TokenCheck
Output
The template "Console App" was created successfully.

Processing post-creation actions...
Restoring /Users/you/source/TokenCheck/TokenCheck.csproj:
Restore succeeded.

dotnet new console creates a console app in a new folder, TokenCheck, and cd moves into it. Then add two packages:

Terminal
dotnet add package Azure.Identity --version 1.21.0
dotnet add package OpenTelemetry.Exporter.OpenTelemetryProtocol --version 1.21.0

Each command adds a package reference to the project and restores it. The first one ends like this:

Output (the last lines of the first command)
info : PackageReference for package 'Azure.Identity' version '1.21.0' added to file '/Users/you/source/TokenCheck/TokenCheck.csproj'.
info : Generating MSBuild file /Users/you/source/TokenCheck/obj/TokenCheck.csproj.nuget.g.targets.
info : Writing assets file to disk. Path: /Users/you/source/TokenCheck/obj/project.assets.json
log : Restored /Users/you/source/TokenCheck/TokenCheck.csproj (in 910 ms).
  • Azure.Identity gives the app AzureCliCredential. Version 1.21.0 brings Azure.Core 1.53.0 with it, which matters for the experimental switch after the steps.
  • OpenTelemetry.Exporter.OpenTelemetryProtocol is the OTLP exporter. It brings the OpenTelemetry SDK with it, so it's the only OpenTelemetry package this app needs.

The project file now lists both:

TokenCheck.csproj
<Project Sdk="Microsoft.NET.Sdk">

<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net10.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Azure.Identity" Version="1.21.0" />
<PackageReference Include="OpenTelemetry.Exporter.OpenTelemetryProtocol" Version="1.21.0" />
</ItemGroup>

</Project>

Open the folder in VS Code, or TokenCheck.csproj in Visual Studio.

Step 2: Listen to the Azure SDK's Spans​

Replace everything in Program.cs with the tracer provider:

Program.cs (the start)
using Azure.Core;
using Azure.Identity;
using OpenTelemetry;
using OpenTelemetry.Resources;
using OpenTelemetry.Trace;

// Collect the spans of every Azure SDK library ("Azure.*") and send them over OTLP
// (http://localhost:4317 by default).
using TracerProvider tracerProvider = Sdk.CreateTracerProviderBuilder()
.ConfigureResource(resource => resource.AddService("TokenCheck"))
.AddSource("Azure.*")
.AddOtlpExporter()
.Build();
  • AddService("TokenCheck") names the app, so the dashboard shows its spans under TokenCheck.
  • AddSource("Azure.*") listens to every source whose name starts with Azure..
  • AddOtlpExporter() sends the spans to localhost:4317, where the dashboard receives them.

There's no AppContext.SetSwitch line: this app doesn't need one, as the section after the steps explains.

Step 3: Ask for Two Tokens​

Add the rest below it:

Program.cs (the rest)
// Your Azure CLI sign-in: the credential runs "az account get-access-token" for you.
AzureCliCredential credential = new();
TokenRequestContext request = new(["https://management.azure.com/.default"]);

for (int i = 1; i <= 2; i++)
{
AccessToken token = await credential.GetTokenAsync(request);
Console.WriteLine($"Token {i}: {token.Token.Length} characters");
}
  • AzureCliCredential gets its tokens from the Azure CLI. Microsoft's Azure CLI documentation: It uses a subprocess to call az account get-access-token to retrieve an access token for the current logged-in account.
  • TokenRequestContext says what the token is for. https://management.azure.com/.default is Azure Resource Manager.
  • The loop asks twice, so there are two calls to compare.
  • Only the length is printed, so the token itself never appears on screen.

Step 4: Run It​

Run dotnet run in VS Code's terminal, or press Ctrl+F5 in Visual Studio:

Terminal
dotnet run
Output
Token 1: 3280 characters
Token 2: 3280 characters

macOS-style terminal window titled Terminal — TokenCheck showing dotnet run printing Token 1: 3280 characters and Token 2: 3280 characters

Both calls worked. The output doesn't say how long each one took, but the spans do.

Step 5: Find the Calls in the Dashboard​

Open the dashboard at http://localhost:18888 and select Traces:

The Traces page of the Aspire Dashboard listing two traces named TokenCheck: AzureCliCredential.GetToken, each with one TokenCheck span, the first taking 1.06s and the second 0.34s

Each call is a trace of its own, named after the app and the span: TokenCheck: AzureCliCredential.GetToken. The first took 1.06 s and the second 0.34 s.

In the Azure SDK's table of credentials that cache tokens, AzureCliCredential has in-memory token caching Not Supported: each call gets its token from the Azure CLI again, so each one shows up as a span of its own. ManagedIdentityCredential, which an app running in Azure uses with a managed identity, has it Supported.

Step 6: Read a Span's Details​

Select the first trace, then the AzureCliCredential.GetToken row, to open the span's details:

The span details pane in the Aspire Dashboard for TokenCheck: AzureCliCredential.GetToken, with Resource TokenCheck and Duration 1.06s, listing the span's Name AzureCliCredential.GetToken, Kind Internal, az.namespace Microsoft.AAD and az.schema_url for OpenTelemetry schema 1.23.0, and under Context the Source Azure.Identity.AzureCliCredential and the TraceId

  • Name, AzureCliCredential.GetToken: the credential and the method that ran.
  • Kind, Internal: the kind the Azure SDK's tracing conventions give the span of a call to a client library's public method.
  • az.namespace, Microsoft.AAD: in the conventions, The Azure Resource Provider Namespace for the service being called.
  • az.schema_url, https://opentelemetry.io/schemas/1.23.0: the version of the OpenTelemetry semantic conventions the attribute names follow.
  • Source, Azure.Identity.AzureCliCredential: the ActivitySource that created the span. Its name starts with Azure., so AddSource("Azure.*") picked it up. The diagnostics guide: Azure SDK ActivitySource names match {root library namespace}.{client name} pattern.

When You Still Need the Experimental Switch​

Many samples turn on Azure SDK tracing with this line at the start of the app:

Program.cs
AppContext.SetSwitch("Azure.Experimental.EnableActivitySource", true);

TokenCheck doesn't have it, and its spans arrived anyway. Azure.Identity 1.21.0 brought in Azure.Core 1.53.0, and the switch stopped being needed for most libraries in Azure.Core 1.36.0, released on 2023-11-10. Its changelog: Distributed tracing with ActivitySource for HTTP and REST-based client libraries is declared stable. Experimental feature-flag is no longer required for most of the newly released libraries. Tracing for messaging libraries remains experimental.

But most isn't all. The diagnostics guide names the messaging libraries, Azure.Messaging.ServiceBus and Azure.Messaging.EventHubs, as still experimental. The Azure Cosmos DB SDK 3.64.0 created no spans at all without the switch when I tried it (How to Trace Azure Cosmos DB Calls with OpenTelemetry in .NET C#). Microsoft's Azure Monitor Distro README still describes the switch, under Enable Azure SDK Instrumentation. It's the switch those libraries still need; for the stable ones, AddSource is enough.

So add the switch when a library you use still needs it, and leave it out otherwise. The diagnostics guide warns that The shape of experimental Activities may change in the future without notice.

The Complete File​

Program.cs
using Azure.Core;
using Azure.Identity;
using OpenTelemetry;
using OpenTelemetry.Resources;
using OpenTelemetry.Trace;

// Collect the spans of every Azure SDK library ("Azure.*") and send them over OTLP
// (http://localhost:4317 by default).
using TracerProvider tracerProvider = Sdk.CreateTracerProviderBuilder()
.ConfigureResource(resource => resource.AddService("TokenCheck"))
.AddSource("Azure.*")
.AddOtlpExporter()
.Build();

// Your Azure CLI sign-in: the credential runs "az account get-access-token" for you.
AzureCliCredential credential = new();
TokenRequestContext request = new(["https://management.azure.com/.default"]);

for (int i = 1; i <= 2; i++)
{
AccessToken token = await credential.GetTokenAsync(request);
Console.WriteLine($"Token {i}: {token.Token.Length} characters");
}

macOS-style code window titled Program.cs — TokenCheck showing a tracer provider that names the service TokenCheck, listens to every source that matches Azure.* and exports over OTLP, then an AzureCliCredential that asks twice for an Azure Resource Manager token and prints only each token's length

Common Mistakes​

MistakeWhat happensDo this instead
Writing AddSource("Azure") without .*It only matches a source named exactly Azure, and Azure SDK sources have longer names, such as Azure.Identity.AzureCliCredentialUse the pattern Azure.*
Dropping the using on the tracer providerActivities might get dropped when the app ends before the provider flushes themKeep using, or dispose the provider at shutdown
Setting the switch in every app, just in caseIt turns on experimental tracing, whose shape may change in the future without noticeSet it only for libraries that still need it
Printing the token to check that it workedThe token ends up on screen and in anything that captures the outputPrint its length, as here

FAQ​

Does the Azure SDK trace HTTP calls too?​

Yes. The diagnostics guide: Azure SDK traces all HTTP calls using Azure.Core.Http source, and Azure.* includes it. AzureCliCredential runs the Azure CLI instead of calling a service itself, so each of TokenCheck's traces has one span. If your app also collects HTTP calls with OpenTelemetry.Instrumentation.Http, the guide shows how to avoid collecting the same calls twice.

Can I turn the switch on without changing code?​

Yes, in two more ways that the diagnostics guide lists. Set the environment variable AZURE_EXPERIMENTAL_ENABLE_ACTIVITY_SOURCE to true, or add this to the project file:

TokenCheck.csproj
<ItemGroup>
<RuntimeHostConfigurationOption Include="Azure.Experimental.EnableActivitySource" Value="true" />
</ItemGroup>

Can I collect only some Azure libraries?​

Yes, with a narrower pattern. The diagnostics guide's example is Azure.Storage.Blobs.* for the Blob Storage clients, and Azure.Storage.* for every Azure Storage library.

Conclusion​

AddSource("Azure.*") collects the spans that Azure SDK libraries create, and the OTLP exporter sends them to the Aspire Dashboard. In TokenCheck, two AzureCliCredential.GetToken calls showed up as spans of 1.06 s and 0.34 s, with no Azure.Experimental.EnableActivitySource switch: since Azure.Core 1.36.0, tracing is stable for most HTTP and REST-based libraries. Keep the switch for the ones that are still experimental, such as the messaging libraries and the Cosmos DB SDK.

Additional Resources​