Enable Azure Monitor OpenTelemetry Exporter for .NET, Node.js, and Python applications (preview)
The Azure Monitor OpenTelemetry Exporter is a component that sends traces (and eventually all application telemetry) to Azure Monitor Application Insights. To learn more about OpenTelemetry concepts, see the OpenTelemetry overview or OpenTelemetry FAQ.
This article describes how to enable and configure the OpenTelemetry-based Azure Monitor Preview offering. After you finish the instructions in this article, you'll be able to send OpenTelemetry traces to Azure Monitor Application Insights.
Important
Azure Monitor OpenTelemetry Exporter for .NET, Node.js, and Python applications is currently in preview. See the Supplemental Terms of Use for Microsoft Azure Previews for legal terms that apply to Azure features that are in beta, preview, or otherwise not yet released into general availability.
Limitations of the preview release
Carefully consider whether this preview is right for you. It enables distributed tracing only and excludes:
- Metrics API (like custom metrics and pre-aggregated metrics)
- Live Metrics
- Logging API (like console logs and logging libraries)
- Autocapture of unhandled exceptions
- Profiler
- Snapshot Debugger
- Offline disk storage and retry logic
- Azure Active Directory authentication
- Sampling
- Autopopulation of Cloud Role Name and Cloud Role Instance in Azure environments
- Autopopulation of User ID and Authenticated User ID when you use the Application Insights JavaScript SDK
- Autopopulation of User IP (to determine location attributes)
- Ability to override Operation Name
- Ability to manually set User ID or Authenticated User ID
- Propagating Operation Name to Dependency Telemetry
- Instrumentation libraries support on Azure Functions
If you require a full-feature experience, use the existing Application Insights ASP.NET or ASP.NET Core SDK until the OpenTelemetry-based offering matures.
Get started
Follow the steps in this section to instrument your application with OpenTelemetry.
Prerequisites
- Azure subscription: Create an Azure subscription for free
- Application Insights resource: Create an Application Insights resource
- Application using an officially supported version of .NET Core or .NET Framework that's at least .NET Framework 4.6.1
Install the client libraries
Install the latest Azure.Monitor.OpenTelemetry.Exporter NuGet package:
dotnet add package --prerelease Azure.Monitor.OpenTelemetry.Exporter
If you get an error like "There are no versions available for the package Azure.Monitor.OpenTelemetry.Exporter," it's probably because the setting of NuGet package sources is missing. Try to specify the source with the -s option:
# Install the latest package with the NuGet package source specified.
dotnet add package --prerelease Azure.Monitor.OpenTelemetry.Exporter -s https://api.nuget.org/v3/index.json
Enable Azure Monitor Application Insights
This section provides guidance that shows how to enable OpenTelemetry.
Add OpenTelemetry instrumentation code
The following code demonstrates how to enable OpenTelemetry in a C# console application by setting up OpenTelemetry TracerProvider. This code must be in the application startup. For ASP.NET Core, it's done typically in the ConfigureServices method of the application Startup class. For ASP.NET applications, it's done typically in Global.asax.cs.
using System.Diagnostics;
using Azure.Monitor.OpenTelemetry.Exporter;
using OpenTelemetry;
using OpenTelemetry.Trace;
public class Program
{
private static readonly ActivitySource MyActivitySource = new ActivitySource(
"OTel.AzureMonitor.Demo");
public static void Main()
{
using var tracerProvider = Sdk.CreateTracerProviderBuilder()
.AddSource("OTel.AzureMonitor.Demo")
.AddAzureMonitorTraceExporter(o =>
{
o.ConnectionString = "<Your Connection String>";
})
.Build();
using (var activity = MyActivitySource.StartActivity("TestActivity"))
{
activity?.SetTag("CustomTag1", "Value1");
activity?.SetTag("CustomTag2", "Value2");
}
System.Console.WriteLine("Press Enter key to exit.");
System.Console.ReadLine();
}
}
Note
The Activity and ActivitySource classes from the System.Diagnostics namespace represent the OpenTelemetry concepts of Span and Tracer, respectively. You create ActivitySource directly by using its constructor instead of by using TracerProvider. Each ActivitySource class must be explicitly connected to TracerProvider by using AddSource(). That's because parts of the OpenTelemetry tracing API are incorporated directly into the .NET runtime. To learn more, see Introduction to OpenTelemetry .NET Tracing API.
Tip
Add instrumentation libraries to autocollect telemetry across popular frameworks and libraries.
Set the Application Insights connection string
Replace the placeholder <Your Connection String> in the preceding code with the connection string from your Application Insights resource.
Confirm data is flowing
Run your application and open your Application Insights Resource tab in the Azure portal. It might take a few minutes for data to show up in the portal.
Note
If you can't run the application or you aren't getting data as expected, see Troubleshooting.
Important
If you have two or more services that emit telemetry to the same Application Insights resource, you're required to set Cloud Role Names to represent them properly on the Application Map.
As part of using Application Insights instrumentation, we collect and send diagnostic data to Microsoft. This data helps us run and improve Application Insights. You have the option to disable nonessential data collection. To learn more, see Statsbeat in Azure Application Insights.
Set the Cloud Role Name and the Cloud Role Instance
You might set the Cloud Role Name and the Cloud Role Instance via Resource attributes. This step updates Cloud Role Name and Cloud Role Instance from their default values to something that makes sense to your team. They'll appear on the Application Map as the name underneath a node. Cloud Role Name uses service.namespace and service.name attributes, although it falls back to service.name if service.namespace isn't set. Cloud Role Instance uses the service.instance.id attribute value.
// Setting role name and role instance
var resourceAttributes = new Dictionary<string, object> {
{ "service.name", "my-service" },
{ "service.namespace", "my-namespace" },
{ "service.instance.id", "my-instance" }};
var resourceBuilder = ResourceBuilder.CreateDefault().AddAttributes(resourceAttributes);
// Done setting role name and role instance
// Set ResourceBuilder on the provider.
using var tracerProvider = Sdk.CreateTracerProviderBuilder()
.SetResourceBuilder(resourceBuilder)
.AddSource("OTel.AzureMonitor.Demo")
.AddAzureMonitorTraceExporter(o =>
{
o.ConnectionString = "<Your Connection String>";
})
.Build();
For information on standard attributes for resources, see Resource Semantic Conventions.
Sampling
Sampling is supported in OpenTelemetry, but it isn't supported in the Azure Monitor OpenTelemetry Exporter at this time.
Warning
Enabling sampling in OpenTelemetry makes standard and log-based metrics extremely inaccurate, which adversely affects all Application Insights experiences. Also, enabling sampling alongside the existing Application Insights SDKs results in broken traces.
Instrumentation libraries
The following libraries are validated to work with the preview release.
Warning
Instrumentation libraries are based on experimental OpenTelemetry specifications. Microsoft's preview support commitment is to ensure that the following libraries emit data to Azure Monitor Application Insights, but it's possible that breaking changes or experimental mapping will block some data elements.
HTTP
- ASP.NET version: 1.0.0-rc7
- ASP.NET Core version: 1.0.0-rc7
- HTTP clients version: 1.0.0-rc7
Database
- SQL client version: 1.0.0-rc7
Note
The preview offering only includes instrumentations that handle HTTP and database requests. To learn more, see OpenTelemetry Semantic Conventions.
Modify telemetry
This section explains how to modify telemetry.
Add span attributes
To add span attributes, use either of the following two ways:
- Use options provided by instrumentation libraries.
- Add a custom span processor.
These attributes might include adding a custom property to your telemetry. You might also use attributes to set optional fields in the Application Insights schema, like Client IP.
Tip
The advantage of using options provided by instrumentation libraries, when they're available, is that the entire context is available. As a result, users can select to add or filter more attributes. For example, the enrich option in the HttpClient instrumentation library gives users access to the httpRequestMessage itself. They can select anything from it and store it as an attribute.
Add a custom property
Any attributes you add to spans are exported as custom properties. They populate the customDimensions field in the requests or the dependencies tables in Application Insights.
Many instrumentation libraries provide an enrich option. For guidance, see the readme files of individual instrumentation libraries:
Use a custom processor:
Tip
Add the processor shown here before the Azure Monitor Exporter.
using var tracerProvider = Sdk.CreateTracerProviderBuilder()
.AddSource("OTel.AzureMonitor.Demo")
.AddProcessor(new ActivityEnrichingProcessor())
.AddAzureMonitorTraceExporter(o =>
{
o.ConnectionString = "<Your Connection String>"
})
.Build();
Add ActivityEnrichingProcessor.cs to your project with the following code:
using System.Diagnostics;
using OpenTelemetry;
using OpenTelemetry.Trace;
public class ActivityEnrichingProcessor : BaseProcessor<Activity>
{
public override void OnEnd(Activity activity)
{
// The updated activity will be available to all processors which are called after this processor.
activity.DisplayName = "Updated-" + activity.DisplayName;
activity.SetTag("CustomDimension1", "Value1");
activity.SetTag("CustomDimension2", "Value2");
}
}
Set the user IP
You can populate the client_IP field for requests by setting the http.client_ip attribute on the span. Application Insights uses the IP address to generate user location attributes and then discards it by default.
Use the add custom property example, but replace the following lines of code in ActivityEnrichingProcessor.cs:
// only applicable in case of activity.Kind == Server
activity.SetTag("http.client_ip", "<IP Address>");
Filter telemetry
You might use the following ways to filter out telemetry before it leaves your application.
Many instrumentation libraries provide a filter option. For guidance, see the readme files of individual instrumentation libraries:
Use a custom processor:
using var tracerProvider = Sdk.CreateTracerProviderBuilder() .AddSource("OTel.AzureMonitor.Demo") .AddProcessor(new ActivityFilteringProcessor()) .AddAzureMonitorTraceExporter(o => { o.ConnectionString = "<Your Connection String>" }) .Build();Add
ActivityFilteringProcessor.csto your project with the following code:using System.Diagnostics; using OpenTelemetry; using OpenTelemetry.Trace; public class ActivityFilteringProcessor : BaseProcessor<Activity> { public override void OnStart(Activity activity) { // prevents all exporters from exporting internal activities if (activity.Kind == ActivityKind.Internal) { activity.IsAllDataRequested = false; } } }If a particular source isn't explicitly added by using
AddSource("ActivitySourceName"), then none of the activities created by using that source will be exported.
Enable the OTLP Exporter
You might want to enable the OpenTelemetry Protocol (OTLP) Exporter alongside your Azure Monitor Exporter to send your telemetry to two locations.
Note
The OTLP Exporter is shown for convenience only. We don't officially support the OTLP Exporter or any components or third-party experiences downstream of it. We suggest you open an issue with the OpenTelemetry-Collector for OpenTelemetry issues outside the Azure support boundary.
Install the OpenTelemetry.Exporter.OpenTelemetryProtocol package along with Azure.Monitor.OpenTelemetry.Exporter in your project.
Add the following code snippet. This example assumes you have an OpenTelemetry Collector with an OTLP receiver running. For details, see the example on GitHub.
// Sends data to Application Insights as well as OTLP using var tracerProvider = Sdk.CreateTracerProviderBuilder() .AddSource("OTel.AzureMonitor.Demo") .AddAzureMonitorTraceExporter(o => { o.ConnectionString = "<Your Connection String>" }) .AddOtlpExporter() .Build();
Troubleshooting
This section provides help with troubleshooting.
Enable diagnostic logging
The Azure Monitor Exporter uses EventSource for its own internal logging. The exporter logs are available to any EventListener by opting into the source named OpenTelemetry-AzureMonitor-Exporter. For troubleshooting steps, see OpenTelemetry Troubleshooting.
Known issues
Known issues for the Azure Monitor OpenTelemetry Exporters include:
- Operation name is missing on dependency telemetry, which adversely affects failures and performance tab experience.
- Device model is missing on request and dependency telemetry, which adversely affects device cohort analysis.
- Database server name is left out of dependency name, which incorrectly aggregates tables with the same name on different servers.
Support
To get support:
- Review troubleshooting steps in this article.
- For Azure support issues, open an Azure support ticket.
For OpenTelemetry issues, contact the OpenTelemetry .NET community directly.
OpenTelemetry feedback
To provide feedback:
- Fill out the OpenTelemetry community's customer feedback survey.
- Tell Microsoft about yourself by joining the OpenTelemetry Early Adopter Community.
- Engage with other Azure Monitor users in the Microsoft Tech Community.
- Make a feature request at the Azure Feedback Forum.
Next steps
- To review the source code, see the Azure Monitor Exporter GitHub repository.
- To install the NuGet package, check for updates, or view release notes, see the Azure Monitor Exporter NuGet Package page.
- To become more familiar with Azure Monitor Application Insights and OpenTelemetry, see the Azure Monitor Example Application.
- To learn more about OpenTelemetry and its community, see the OpenTelemetry .NET GitHub repository.
- To enable usage experiences, enable web or browser user monitoring.
Maklum balas
Kirim dan lihat maklum balas untuk