Use one of the following three ways to configure the connection string:
Add UseAzureMonitor() to your program.cs file:
var builder = WebApplication.CreateBuilder(args);
// Add the OpenTelemetry telemetry service to the application.
// This service will collect and send telemetry data to Azure Monitor.
builder.Services.AddOpenTelemetry().UseAzureMonitor(options => {
options.ConnectionString = "<Your Connection String>";
});
var app = builder.Build();
app.Run();
If you set the connection string in more than one place, we adhere to the following precedence:
Code
Environment Variable
Configuration File
Use one of the following two ways to configure the connection string:
Add the Azure Monitor Exporter to each OpenTelemetry signal in application startup.
// Create a new OpenTelemetry tracer provider.
// It is important to keep the TracerProvider instance active throughout the process lifetime.
var tracerProvider = Sdk.CreateTracerProviderBuilder()
.AddAzureMonitorTraceExporter(options =>
{
options.ConnectionString = "<Your Connection String>";
});
// Create a new OpenTelemetry meter provider.
// It is important to keep the MetricsProvider instance active throughout the process lifetime.
var metricsProvider = Sdk.CreateMeterProviderBuilder()
.AddAzureMonitorMetricExporter(options =>
{
options.ConnectionString = "<Your Connection String>";
});
// Create a new logger factory.
// It is important to keep the LoggerFactory instance active throughout the process lifetime.
var loggerFactory = LoggerFactory.Create(builder =>
{
builder.AddOpenTelemetry(options =>
{
options.AddAzureMonitorLogExporter(options =>
{
options.ConnectionString = "<Your Connection String>";
});
});
});
// Import the useAzureMonitor function and the AzureMonitorOpenTelemetryOptions class from the @azure/monitor-opentelemetry package.
const { useAzureMonitor, AzureMonitorOpenTelemetryOptions } = require("@azure/monitor-opentelemetry");
// Create a new AzureMonitorOpenTelemetryOptions object.
const options: AzureMonitorOpenTelemetryOptions = {
azureMonitorExporterOptions: {
connectionString: "<your connection string>"
}
};
// Enable Azure Monitor integration using the useAzureMonitor function and the AzureMonitorOpenTelemetryOptions object.
useAzureMonitor(options);
Use one of the following two ways to configure the connection string:
# Import the `configure_azure_monitor()` function from the `azure.monitor.opentelemetry` package.
from azure.monitor.opentelemetry import configure_azure_monitor
# Configure OpenTelemetry to use Azure Monitor with the specified connection string.
# Replace `<your-connection-string>` with the connection string of your Azure Monitor Application Insights resource.
configure_azure_monitor(
connection_string="<your-connection-string>",
)
Set the Cloud Role Name and the Cloud Role Instance
For supported languages, the Azure Monitor OpenTelemetry Distro automatically detects the resource context and provides default values for the Cloud Role Name and the Cloud Role Instance properties of your component. However, you might want to override the default values to something that makes sense to your team. The cloud role name value appears on the Application Map as the name underneath a node.
Set the Cloud Role Name and the Cloud Role Instance via Resource attributes. 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. For information on standard attributes for resources, see OpenTelemetry Semantic Conventions.
// Setting role name and role instance
// Create a dictionary of resource attributes.
var resourceAttributes = new Dictionary<string, object> {
{ "service.name", "my-service" },
{ "service.namespace", "my-namespace" },
{ "service.instance.id", "my-instance" }};
// Create a new ASP.NET Core web application builder.
var builder = WebApplication.CreateBuilder(args);
// Add the OpenTelemetry telemetry service to the application.
// This service will collect and send telemetry data to Azure Monitor.
builder.Services.AddOpenTelemetry()
.UseAzureMonitor()
// Configure the ResourceBuilder to add the custom resource attributes to all signals.
// Custom resource attributes should be added AFTER AzureMonitor to override the default ResourceDetectors.
.ConfigureResource(resourceBuilder => resourceBuilder.AddAttributes(_testResourceAttributes));
// Build the ASP.NET Core web application.
var app = builder.Build();
// Start the ASP.NET Core web application.
app.Run();
Set the Cloud Role Name and the Cloud Role Instance via Resource attributes. 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. For information on standard attributes for resources, see OpenTelemetry Semantic Conventions.
// Setting role name and role instance
// Create a dictionary of resource attributes.
var resourceAttributes = new Dictionary<string, object> {
{ "service.name", "my-service" },
{ "service.namespace", "my-namespace" },
{ "service.instance.id", "my-instance" }};
// Create a resource builder.
var resourceBuilder = ResourceBuilder.CreateDefault().AddAttributes(resourceAttributes);
// Create a new OpenTelemetry tracer provider and set the resource builder.
// It is important to keep the TracerProvider instance active throughout the process lifetime.
var tracerProvider = Sdk.CreateTracerProviderBuilder()
// Set ResourceBuilder on the TracerProvider.
.SetResourceBuilder(resourceBuilder)
.AddAzureMonitorTraceExporter();
// Create a new OpenTelemetry meter provider and set the resource builder.
// It is important to keep the MetricsProvider instance active throughout the process lifetime.
var metricsProvider = Sdk.CreateMeterProviderBuilder()
// Set ResourceBuilder on the MeterProvider.
.SetResourceBuilder(resourceBuilder)
.AddAzureMonitorMetricExporter();
// Create a new logger factory and add the OpenTelemetry logger provider with the resource builder.
// It is important to keep the LoggerFactory instance active throughout the process lifetime.
var loggerFactory = LoggerFactory.Create(builder =>
{
builder.AddOpenTelemetry(options =>
{
// Set ResourceBuilder on the Logging config.
options.SetResourceBuilder(resourceBuilder);
options.AddAzureMonitorLogExporter();
});
});
Use the spring.application.name for Spring Boot native image applications
Use the quarkus.application.name for Quarkus native image applications
Set the Cloud Role Name and the Cloud Role Instance via Resource attributes. 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. For information on standard attributes for resources, see OpenTelemetry Semantic Conventions.
// Import the useAzureMonitor function, the AzureMonitorOpenTelemetryOptions class, the Resource class, and the SemanticResourceAttributes class from the @azure/monitor-opentelemetry, @opentelemetry/resources, and @opentelemetry/semantic-conventions packages, respectively.
const { useAzureMonitor, AzureMonitorOpenTelemetryOptions } = require("@azure/monitor-opentelemetry");
const { Resource } = require("@opentelemetry/resources");
const { SemanticResourceAttributes } = require("@opentelemetry/semantic-conventions");
// Create a new Resource object with the following custom resource attributes:
//
// * service_name: my-service
// * service_namespace: my-namespace
// * service_instance_id: my-instance
const customResource = new Resource({
[SemanticResourceAttributes.SERVICE_NAME]: "my-service",
[SemanticResourceAttributes.SERVICE_NAMESPACE]: "my-namespace",
[SemanticResourceAttributes.SERVICE_INSTANCE_ID]: "my-instance",
});
// Create a new AzureMonitorOpenTelemetryOptions object and set the resource property to the customResource object.
const options: AzureMonitorOpenTelemetryOptions = {
resource: customResource
};
// Enable Azure Monitor integration using the useAzureMonitor function and the AzureMonitorOpenTelemetryOptions object.
useAzureMonitor(options);
Set the Cloud Role Name and the Cloud Role Instance via Resource attributes. 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. For information on standard attributes for resources, see OpenTelemetry Semantic Conventions.
Set Resource attributes using the OTEL_RESOURCE_ATTRIBUTES and/or OTEL_SERVICE_NAME environment variables. OTEL_RESOURCE_ATTRIBUTES takes series of comma-separated key-value pairs. For example, to set the Cloud Role Name to my-namespace.my-helloworld-service and set Cloud Role Instance to my-instance, you can set OTEL_RESOURCE_ATTRIBUTES and OTEL_SERVICE_NAME as such:
If you don't set the service.namespace Resource attribute, you can alternatively set the Cloud Role Name with only the OTEL_SERVICE_NAME environment variable or the service.name Resource attribute. For example, to set the Cloud Role Name to my-helloworld-service and set Cloud Role Instance to my-instance, you can set OTEL_RESOURCE_ATTRIBUTES and OTEL_SERVICE_NAME as such:
You might want to enable sampling to reduce your data ingestion volume, which reduces your cost. Azure Monitor provides a custom fixed-rate sampler that populates events with a sampling ratio, which Application Insights converts to ItemCount. The fixed-rate sampler ensures accurate experiences and event counts. The sampler is designed to preserve your traces across services, and it's interoperable with older Application Insights Software Development Kits (SDKs). For more information, see Learn More about sampling.
The sampler expects a sample rate of between 0 and 1 inclusive. A rate of 0.1 means approximately 10% of your traces are sent.
// Create a new ASP.NET Core web application builder.
var builder = WebApplication.CreateBuilder(args);
// Add the OpenTelemetry telemetry service to the application.
// This service will collect and send telemetry data to Azure Monitor.
builder.Services.AddOpenTelemetry().UseAzureMonitor(o =>
{
// Set the sampling ratio to 10%. This means that 10% of all traces will be sampled and sent to Azure Monitor.
o.SamplingRatio = 0.1F;
});
// Build the ASP.NET Core web application.
var app = builder.Build();
// Start the ASP.NET Core web application.
app.Run();
The sampler expects a sample rate of between 0 and 1 inclusive. A rate of 0.1 means approximately 10% of your traces are sent.
// Create a new OpenTelemetry tracer provider.
// It is important to keep the TracerProvider instance active throughout the process lifetime.
var tracerProvider = Sdk.CreateTracerProviderBuilder()
.AddAzureMonitorTraceExporter(options =>
{
// Set the sampling ratio to 10%. This means that 10% of all traces will be sampled and sent to Azure Monitor.
options.SamplingRatio = 0.1F;
});
Starting from 3.4.0, rate-limited sampling is available and is now the default. For more information about sampling, see Java sampling.
The sampler expects a sample rate of between 0 and 1 inclusive. A rate of 0.1 means approximately 10% of your traces are sent.
// Import the useAzureMonitor function and the AzureMonitorOpenTelemetryOptions class from the @azure/monitor-opentelemetry package.
const { useAzureMonitor, AzureMonitorOpenTelemetryOptions } = require("@azure/monitor-opentelemetry");
// Create a new AzureMonitorOpenTelemetryOptions object and set the samplingRatio property to 0.1.
const options: AzureMonitorOpenTelemetryOptions = {
samplingRatio: 0.1
};
// Enable Azure Monitor integration using the useAzureMonitor function and the AzureMonitorOpenTelemetryOptions object.
useAzureMonitor(options);
The configure_azure_monitor() function automatically utilizes
ApplicationInsightsSampler for compatibility with Application Insights SDKs and
to sample your telemetry. The OTEL_TRACES_SAMPLER_ARG environment variable can be used to specify
the sampling rate, with a valid range of 0 to 1, where 0 is 0% and 1 is 100%.
For example, a value of 0.1 means 10% of your traces are sent.
export OTEL_TRACES_SAMPLER_ARG=0.1
Tip
When using fixed-rate/percentage sampling and you aren't sure what to set the sampling rate as, start at 5% (i.e., 0.05 sampling ratio) and adjust the rate based on the accuracy of the operations shown in the failures and performance panes. A higher rate generally results in higher accuracy. However, ANY sampling will affect accuracy so we recommend alerting on OpenTelemetry metrics, which are unaffected by sampling.
Live metrics
Live metrics provides a real-time analytics dashboard for insight into application activity and performance.
See the Supplemental Terms of Use for Azure Previews for legal terms that apply to Azure features that are in beta, preview, or otherwise not yet released into general availability.
This feature is enabled by default.
Users can disable Live Metrics when configuring the Distro.
builder.Services.AddOpenTelemetry().UseAzureMonitor(options => {
// Disable the Live Metrics feature.
options.EnableLiveMetrics = false;
});
This feature isn't available in the Azure Monitor .NET Exporter.
The Live Metrics experience is enabled by default.
Enable Microsoft Entra ID (formerly Azure AD) authentication
You might want to enable Microsoft Entra authentication for a more secure connection to Azure, which prevents unauthorized telemetry from being ingested into your subscription.
// Create a new ASP.NET Core web application builder.
var builder = WebApplication.CreateBuilder(args);
// Add the OpenTelemetry telemetry service to the application.
// This service will collect and send telemetry data to Azure Monitor.
builder.Services.AddOpenTelemetry().UseAzureMonitor(options => {
// Set the Azure Monitor credential to the DefaultAzureCredential.
// This credential will use the Azure identity of the current user or
// the service principal that the application is running as to authenticate
// to Azure Monitor.
options.Credential = new DefaultAzureCredential();
});
// Build the ASP.NET Core web application.
var app = builder.Build();
// Start the ASP.NET Core web application.
app.Run();
We support the credential classes provided by Azure Identity.
We recommend DefaultAzureCredential for local development.
We recommend ManagedIdentityCredential for system-assigned and user-assigned managed identities.
For system-assigned, use the default constructor without parameters.
For user-assigned, provide the client ID to the constructor.
We recommend ClientSecretCredential for service principals.
Provide the tenant ID, client ID, and client secret to the constructor.
// Create a DefaultAzureCredential.
var credential = new DefaultAzureCredential();
// Create a new OpenTelemetry tracer provider and set the credential.
// It is important to keep the TracerProvider instance active throughout the process lifetime.
var tracerProvider = Sdk.CreateTracerProviderBuilder()
.AddAzureMonitorTraceExporter(options =>
{
options.Credential = credential;
});
// Create a new OpenTelemetry meter provider and set the credential.
// It is important to keep the MetricsProvider instance active throughout the process lifetime.
var metricsProvider = Sdk.CreateMeterProviderBuilder()
.AddAzureMonitorMetricExporter(options =>
{
options.Credential = credential;
});
// Create a new logger factory and add the OpenTelemetry logger provider with the credential.
// It is important to keep the LoggerFactory instance active throughout the process lifetime.
var loggerFactory = LoggerFactory.Create(builder =>
{
builder.AddOpenTelemetry(options =>
{
options.AddAzureMonitorLogExporter(options =>
{
options.Credential = credential;
});
});
});
Microsoft Entra ID authentication is not available for GraalVM Native applications.
We support the credential classes provided by Azure Identity.
// Import the useAzureMonitor function, the AzureMonitorOpenTelemetryOptions class, and the ManagedIdentityCredential class from the @azure/monitor-opentelemetry and @azure/identity packages, respectively.
const { useAzureMonitor, AzureMonitorOpenTelemetryOptions } = require("@azure/monitor-opentelemetry");
const { ManagedIdentityCredential } = require("@azure/identity");
// Create a new ManagedIdentityCredential object.
const credential = new ManagedIdentityCredential();
// Create a new AzureMonitorOpenTelemetryOptions object and set the credential property to the credential object.
const options: AzureMonitorOpenTelemetryOptions = {
azureMonitorExporterOptions: {
connectionString:
process.env["APPLICATIONINSIGHTS_CONNECTION_STRING"] || "<your connection string>",
credential: credential
}
};
// Enable Azure Monitor integration using the useAzureMonitor function and the AzureMonitorOpenTelemetryOptions object.
useAzureMonitor(options);
Azure Monitor OpenTelemetry Distro for Python support the credential classes provided by Azure Identity.
We recommend DefaultAzureCredential for local development.
We recommend ManagedIdentityCredential for system-assigned and user-assigned managed identities.
For system-assigned, use the default constructor without parameters.
For user-assigned, provide the client_id to the constructor.
We recommend ClientSecretCredential for service principals.
Provide the tenant ID, client ID, and client secret to the constructor.
If using ManagedIdentityCredential
# Import the `ManagedIdentityCredential` class from the `azure.identity` package.
from azure.identity import ManagedIdentityCredential
# Import the `configure_azure_monitor()` function from the `azure.monitor.opentelemetry` package.
from azure.monitor.opentelemetry import configure_azure_monitor
from opentelemetry import trace
# Configure the Distro to authenticate with Azure Monitor using a managed identity credential.
credential = ManagedIdentityCredential(client_id="<client_id>")
configure_azure_monitor(
connection_string="your-connection-string",
credential=credential,
)
tracer = trace.get_tracer(__name__)
with tracer.start_as_current_span("hello with aad managed identity"):
print("Hello, World!")
If using ClientSecretCredential
# Import the `ClientSecretCredential` class from the `azure.identity` package.
from azure.identity import ClientSecretCredential
# Import the `configure_azure_monitor()` function from the `azure.monitor.opentelemetry` package.
from azure.monitor.opentelemetry import configure_azure_monitor
from opentelemetry import trace
# Configure the Distro to authenticate with Azure Monitor using a client secret credential.
credential = ClientSecretCredential(
tenant_id="<tenant_id",
client_id="<client_id>",
client_secret="<client_secret>",
)
configure_azure_monitor(
connection_string="your-connection-string",
credential=credential,
)
with tracer.start_as_current_span("hello with aad client secret identity"):
print("Hello, World!")
Offline Storage and Automatic Retries
To improve reliability and resiliency, Azure Monitor OpenTelemetry-based offerings write to offline/local storage by default when an application loses its connection with Application Insights. It saves the application telemetry to disk and periodically tries to send it again for up to 48 hours. In high-load applications, telemetry is occasionally dropped for two reasons. First, when the allowable time is exceeded, and second, when the maximum file size is exceeded or the SDK doesn't have an opportunity to clear out the file. If we need to choose, the product saves more recent events over old ones. Learn More
The Distro package includes the AzureMonitorExporter, which by default uses one of the following locations for offline storage (listed in order of precedence):
Windows
%LOCALAPPDATA%\Microsoft\AzureMonitor
%TEMP%\Microsoft\AzureMonitor
Non-Windows
%TMPDIR%/Microsoft/AzureMonitor
/var/tmp/Microsoft/AzureMonitor
/tmp/Microsoft/AzureMonitor
To override the default directory, you should set AzureMonitorOptions.StorageDirectory.
// Create a new ASP.NET Core web application builder.
var builder = WebApplication.CreateBuilder(args);
// Add the OpenTelemetry telemetry service to the application.
// This service will collect and send telemetry data to Azure Monitor.
builder.Services.AddOpenTelemetry().UseAzureMonitor(options =>
{
// Set the Azure Monitor storage directory to "C:\\SomeDirectory".
// This is the directory where the OpenTelemetry SDK will store any telemetry data that cannot be sent to Azure Monitor immediately.
options.StorageDirectory = "C:\\SomeDirectory";
});
// Build the ASP.NET Core web application.
var app = builder.Build();
// Start the ASP.NET Core web application.
app.Run();
To disable this feature, you should set AzureMonitorOptions.DisableOfflineStorage = true.
By default, the AzureMonitorExporter uses one of the following locations for offline storage (listed in order of precedence):
Windows
%LOCALAPPDATA%\Microsoft\AzureMonitor
%TEMP%\Microsoft\AzureMonitor
Non-Windows
%TMPDIR%/Microsoft/AzureMonitor
/var/tmp/Microsoft/AzureMonitor
/tmp/Microsoft/AzureMonitor
To override the default directory, you should set AzureMonitorExporterOptions.StorageDirectory.
// Create a new OpenTelemetry tracer provider and set the storage directory.
// It is important to keep the TracerProvider instance active throughout the process lifetime.
var tracerProvider = Sdk.CreateTracerProviderBuilder()
.AddAzureMonitorTraceExporter(options =>
{
// Set the Azure Monitor storage directory to "C:\\SomeDirectory".
// This is the directory where the OpenTelemetry SDK will store any trace data that cannot be sent to Azure Monitor immediately.
options.StorageDirectory = "C:\\SomeDirectory";
});
// Create a new OpenTelemetry meter provider and set the storage directory.
// It is important to keep the MetricsProvider instance active throughout the process lifetime.
var metricsProvider = Sdk.CreateMeterProviderBuilder()
.AddAzureMonitorMetricExporter(options =>
{
// Set the Azure Monitor storage directory to "C:\\SomeDirectory".
// This is the directory where the OpenTelemetry SDK will store any metric data that cannot be sent to Azure Monitor immediately.
options.StorageDirectory = "C:\\SomeDirectory";
});
// Create a new logger factory and add the OpenTelemetry logger provider with the storage directory.
// It is important to keep the LoggerFactory instance active throughout the process lifetime.
var loggerFactory = LoggerFactory.Create(builder =>
{
builder.AddOpenTelemetry(options =>
{
options.AddAzureMonitorLogExporter(options =>
{
// Set the Azure Monitor storage directory to "C:\\SomeDirectory".
// This is the directory where the OpenTelemetry SDK will store any log data that cannot be sent to Azure Monitor immediately.
options.StorageDirectory = "C:\\SomeDirectory";
});
});
});
To disable this feature, you should set AzureMonitorExporterOptions.DisableOfflineStorage = true.
Configuring Offline Storage and Automatic Retries isn't available in Java.
Configuring Offline Storage and Automatic Retries isn't available in Java native image applications.
By default, the AzureMonitorExporter uses one of the following locations for offline storage.
Windows
%TEMP%\Microsoft\AzureMonitor
Non-Windows
%TMPDIR%/Microsoft/AzureMonitor
/var/tmp/Microsoft/AzureMonitor
To override the default directory, you should set storageDirectory.
For example:
// Import the useAzureMonitor function and the AzureMonitorOpenTelemetryOptions class from the @azure/monitor-opentelemetry package.
const { useAzureMonitor, AzureMonitorOpenTelemetryOptions } = require("@azure/monitor-opentelemetry");
// Create a new AzureMonitorOpenTelemetryOptions object and set the azureMonitorExporterOptions property to an object with the following properties:
//
// * connectionString: The connection string for your Azure Monitor Application Insights resource.
// * storageDirectory: The directory where the Azure Monitor OpenTelemetry exporter will store telemetry data when it is offline.
// * disableOfflineStorage: A boolean value that specifies whether to disable offline storage.
const options: AzureMonitorOpenTelemetryOptions = {
azureMonitorExporterOptions: {
connectionString: "<Your Connection String>",
storageDirectory: "C:\\SomeDirectory",
disableOfflineStorage: false
}
};
// Enable Azure Monitor integration using the useAzureMonitor function and the AzureMonitorOpenTelemetryOptions object.
useAzureMonitor(options);
To disable this feature, you should set disableOfflineStorage = true.
By default, Azure Monitor exporters use the following path:
To override the default directory, you should set storage_directory to the directory you want.
For example:
...
# Configure OpenTelemetry to use Azure Monitor with the specified connection string and storage directory.
# Replace `your-connection-string` with the connection string to your Azure Monitor Application Insights resource.
# Replace `C:\\SomeDirectory` with the directory where you want to store the telemetry data before it is sent to Azure Monitor.
configure_azure_monitor(
connection_string="your-connection-string",
storage_directory="C:\\SomeDirectory",
)
...
To disable this feature, you should set disable_offline_storage to True. Defaults to False.
For example:
...
# Configure OpenTelemetry to use Azure Monitor with the specified connection string and disable offline storage.
# Replace `your-connection-string` with the connection string to your Azure Monitor Application Insights resource.
configure_azure_monitor(
connection_string="your-connection-string",
disable_offline_storage=True,
)
...
Enable the OTLP Exporter
You might want to enable the OpenTelemetry Protocol (OTLP) Exporter alongside the 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.
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.
// Create a new ASP.NET Core web application builder.
var builder = WebApplication.CreateBuilder(args);
// Add the OpenTelemetry telemetry service to the application.
// This service will collect and send telemetry data to Azure Monitor.
builder.Services.AddOpenTelemetry().UseAzureMonitor();
// Add the OpenTelemetry OTLP exporter to the application.
// This exporter will send telemetry data to an OTLP receiver, such as Prometheus
builder.Services.AddOpenTelemetry().WithTracing(builder => builder.AddOtlpExporter());
builder.Services.AddOpenTelemetry().WithMetrics(builder => builder.AddOtlpExporter());
// Build the ASP.NET Core web application.
var app = builder.Build();
// Start the ASP.NET Core web application.
app.Run();
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.
// Create a new OpenTelemetry tracer provider and add the Azure Monitor trace exporter and the OTLP trace exporter.
// It is important to keep the TracerProvider instance active throughout the process lifetime.
var tracerProvider = Sdk.CreateTracerProviderBuilder()
.AddAzureMonitorTraceExporter()
.AddOtlpExporter();
// Create a new OpenTelemetry meter provider and add the Azure Monitor metric exporter and the OTLP metric exporter.
// It is important to keep the MetricsProvider instance active throughout the process lifetime.
var metricsProvider = Sdk.CreateMeterProviderBuilder()
.AddAzureMonitorMetricExporter()
.AddOtlpExporter();
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.
// Import the useAzureMonitor function, the AzureMonitorOpenTelemetryOptions class, the trace module, the ProxyTracerProvider class, the BatchSpanProcessor class, the NodeTracerProvider class, and the OTLPTraceExporter class from the @azure/monitor-opentelemetry, @opentelemetry/api, @opentelemetry/sdk-trace-base, @opentelemetry/sdk-trace-node, and @opentelemetry/exporter-trace-otlp-http packages, respectively.
const { useAzureMonitor, AzureMonitorOpenTelemetryOptions } = require("@azure/monitor-opentelemetry");
const { BatchSpanProcessor } = require('@opentelemetry/sdk-trace-base');
const { OTLPTraceExporter } = require('@opentelemetry/exporter-trace-otlp-http');
// Create a new OTLPTraceExporter object.
const otlpExporter = new OTLPTraceExporter();
// Enable Azure Monitor integration.
const options: AzureMonitorOpenTelemetryOptions = {
// Add the SpanEnrichingProcessor
spanProcessors: [new BatchSpanProcessor(otlpExporter)]
}
useAzureMonitor(options);
Add the following code snippet. This example assumes you have an OpenTelemetry Collector with an OTLP receiver running. For details, see this README.
# Import the `configure_azure_monitor()`, `trace`, `OTLPSpanExporter`, and `BatchSpanProcessor` classes from the appropriate packages.
from azure.monitor.opentelemetry import configure_azure_monitor
from opentelemetry import trace
from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter
from opentelemetry.sdk.trace.export import BatchSpanProcessor
# Configure OpenTelemetry to use Azure Monitor with the specified connection string.
# Replace `<your-connection-string>` with the connection string to your Azure Monitor Application Insights resource.
configure_azure_monitor(
connection_string="<your-connection-string>",
)
# Get the tracer for the current module.
tracer = trace.get_tracer(__name__)
# Create an OTLP span exporter that sends spans to the specified endpoint.
# Replace `http://localhost:4317` with the endpoint of your OTLP collector.
otlp_exporter = OTLPSpanExporter(endpoint="http://localhost:4317")
# Create a batch span processor that uses the OTLP span exporter.
span_processor = BatchSpanProcessor(otlp_exporter)
# Add the batch span processor to the tracer provider.
trace.get_tracer_provider().add_span_processor(span_processor)
# Start a new span with the name "test".
with tracer.start_as_current_span("test"):
print("Hello world!")
OpenTelemetry configurations
The following OpenTelemetry configurations can be accessed through environment variables while using the Azure Monitor OpenTelemetry Distros.
Set it to the connection string for your Application Insights resource.
APPLICATIONINSIGHTS_STATSBEAT_DISABLED
Set it to true to opt out of internal metrics collection.
OTEL_RESOURCE_ATTRIBUTES
Key-value pairs to be used as resource attributes. For more information about resource attributes, see the Resource SDK specification.
OTEL_SERVICE_NAME
Sets the value of the service.name resource attribute. If service.name is also provided in OTEL_RESOURCE_ATTRIBUTES, then OTEL_SERVICE_NAME takes precedence.
Environment variable
Description
APPLICATIONINSIGHTS_CONNECTION_STRING
Set it to the connection string for your Application Insights resource.
APPLICATIONINSIGHTS_STATSBEAT_DISABLED
Set it to true to opt out of internal metrics collection.
OTEL_RESOURCE_ATTRIBUTES
Key-value pairs to be used as resource attributes. For more information about resource attributes, see the Resource SDK specification.
OTEL_SERVICE_NAME
Sets the value of the service.name resource attribute. If service.name is also provided in OTEL_RESOURCE_ATTRIBUTES, then OTEL_SERVICE_NAME takes precedence.
You can think of it as a thin wrapper that bundles together all the OpenTelemetry components for a first-class experience on Azure. This wrapper is also called a distribution in OpenTelemetry.
Why should I use the Azure Monitor OpenTelemetry Distro?
There are several advantages to using the Azure Monitor OpenTelemetry Distro over native OpenTelemetry from the community:
Reduces enablement effort
Supported by Microsoft
Brings in Azure-specific features such as:
Sampling compatible with classic Application Insights SDKs
In the spirit of OpenTelemetry, we designed the distro to be open and extensible. For example, you can add:
An OpenTelemetry Protocol (OTLP) exporter and send to a second destination simultaneously
Other instrumentation libraries not included in the distro
Because the Distro provides an OpenTelemetry distribution, the Distro supports anything supported by OpenTelemetry. For example, you can add more telemetry processors, exporters, or instrumentation libraries, if OpenTelemetry supports them.
Note
The Distro sets the sampler to a custom, fixed-rate sampler for Application Insights. You can change this to a different sampler, but doing so might disable some of the Distro's included capabilities.
For more information about the supported sampler, see the Enable Sampling section of Configure Azure Monitor OpenTelemetry.
For languages without a supported standalone OpenTelemetry exporter, the Azure Monitor OpenTelemetry Distro is the only currently supported way to use OpenTelemetry with Azure Monitor. For languages with a supported standalone OpenTelemetry exporter, you have the option of using either the Azure Monitor OpenTelemetry Distro or the appropriate standalone OpenTelemetry exporter depending on your telemetry scenario. For more information, see When should I use the Azure Monitor OpenTelemetry exporter?.
How can I test out the Azure Monitor OpenTelemetry Distro?
Adopting OpenTelemetry now prevents having to migrate at a later date.
When should I use the Azure Monitor OpenTelemetry exporter?
For ASP.NET Core, Java, Node.js, and Python, we recommend using the Azure Monitor OpenTelemetry Distro. It's one line of code to get started.
For all other .NET scenarios, including classic ASP.NET, console apps, Windows Forms (WinForms), etc., we recommend using the .NET Azure Monitor OpenTelemetry exporter: Azure.Monitor.OpenTelemetry.Exporter.
For more complex Python telemetry scenarios that require advanced configuration, we recommend using the Python Azure Monitor OpenTelemetry Exporter.
What's the current release state of features within the Azure Monitor OpenTelemetry Distro?
The following chart breaks out OpenTelemetry feature support for each language.
❌ This feature isn't available or isn't applicable.
Can OpenTelemetry be used for web browsers?
Yes, but we don't recommend it and Azure doesn't support it. OpenTelemetry JavaScript is heavily optimized for Node.js. Instead, we recommend using the Application Insights JavaScript SDK.
When can we expect the OpenTelemetry SDK to be available for use in web browsers?
The OpenTelemetry web SDK doesn't have a determined availability timeline. We're likely several years away from a browser SDK that is a viable alternative to the Application Insights JavaScript SDK.
Can I test OpenTelemetry in a web browser today?
The OpenTelemetry web sandbox is a fork designed to make OpenTelemetry work in a browser. It's not yet possible to send telemetry to Application Insights. The SDK doesn't define general client events.
Is running Application Insights alongside competitor agents like AppDynamics, DataDog, and NewRelic supported?
This practice isn't something we plan to test or support, although our Distros allow you to export to an OTLP endpoint alongside Azure Monitor simultaneously.
Can I use preview features in production environments?
Some customers use the OpenTelemetry Collector as an agent alternative, even though Microsoft doesn't officially support an agent-based approach for application monitoring yet. In the meantime, the open-source community contributed an OpenTelemetry Collector Azure Monitor Exporter that some customers are using to send data to Azure Monitor Application Insights. This is not supported by Microsoft.
What's the difference between OpenCensus and OpenTelemetry?
OpenCensus is the precursor to OpenTelemetry. Microsoft helped bring together OpenTracing and OpenCensus to create OpenTelemetry, a single observability standard for the world. The current production-recommended Python SDK for Azure Monitor is based on OpenCensus. Microsoft is committed to making Azure Monitor based on OpenTelemetry.
In Grafana, why do I see Status: 500. Can't visualize trace events using the trace visualizer?
You could be trying to visualize raw text logs rather than OpenTelemetry traces.
In Application Insights, the 'Traces' table stores raw text logs for diagnostic purposes. They aid in identifying and correlating traces associated with user requests, other events, and exception reports. However, the 'Traces' table doesn't directly contribute to the end-to-end transaction view (waterfall chart) in visualization tools like Grafana.
With the growing adoption of cloud-native practices, there's an evolution in telemetry collection and terminology. OpenTelemetry became a standard for collecting and instrumenting telemetry data. In this context, the term 'Traces' took on a new meaning. Rather than raw logs, 'Traces' in OpenTelemetry refer to a richer, structured form of telemetry that includes spans, which represent individual units of work. These spans are crucial for constructing detailed transaction views, enabling better monitoring and diagnostics of cloud-native applications.
The Azure Monitor Exporter uses EventSource for its internal logging. The exporter logs are available to any EventListener by opting in to the source that's named OpenTelemetry-AzureMonitor-Exporter. For troubleshooting steps, see OpenTelemetry Troubleshooting on GitHub.
Step 2: Test connectivity between your application host and the ingestion service
Application Insights SDKs and agents send telemetry to get ingested as REST calls at our ingestion endpoints. To test connectivity from your web server or application host computer to the ingestion service endpoints, use cURL commands or raw REST requests from PowerShell. For more information, see Troubleshoot missing application telemetry in Azure Monitor Application Insights.
Known issues
The following items are known issues for the Azure Monitor OpenTelemetry Exporters:
The operation name is missing from dependency telemetry. The missing operation name causes failures and adversely affects performance tab experience.
The device model is missing from request and dependency telemetry. The missing device model adversely affects device cohort analysis.
Step 1: Enable diagnostic logging
The Azure Monitor Exporter uses EventSource for its internal logging. The exporter logs are available to any EventListener by opting in to the source that's named OpenTelemetry-AzureMonitor-Exporter. For troubleshooting steps, see OpenTelemetry Troubleshooting on GitHub.
Step 2: Test connectivity between your application host and the ingestion service
Application Insights SDKs and agents send telemetry to get ingested as REST calls at our ingestion endpoints. To test connectivity from your web server or application host computer to the ingestion service endpoints, use cURL commands or raw REST requests from PowerShell. For more information, see Troubleshoot missing application telemetry in Azure Monitor Application Insights.
Known issues
The following items are known issues for the Azure Monitor OpenTelemetry Exporters:
The operation name is missing from dependency telemetry. The missing operation name causes failures and adversely affects performance tab experience.
The device model is missing from request and dependency telemetry. The missing device model adversely affects device cohort analysis.
Step 2: Test connectivity between your application host and the ingestion service
Application Insights SDKs and agents send telemetry to get ingested as REST calls at our ingestion endpoints. To test connectivity from your web server or application host computer to the ingestion service endpoints, use cURL commands or raw REST requests from PowerShell. For more information, see Troubleshoot missing application telemetry in Azure Monitor Application Insights.
Known issues
If you download the Application Insights client library for installation from a browser, sometimes the downloaded JAR file is corrupted and is about half the size of the source file. If you experience this problem, download the JAR file by running the curl or wget command, as shown in the following example command calls:
The example command calls apply to Application Insights for Java version 3.4.11. To find the version number and URL address of the current release of Application Insights for Java, see https://github.com/microsoft/ApplicationInsights-Java/releases.
The following steps are applicable to Spring Boot native applications.
Step 1: Verify the OpenTelemetry version
You might notice the following message during the application startup:
WARN c.a.m.a.s.OpenTelemetryVersionCheckRunner - The OpenTelemetry version is not compatible with the spring-cloud-azure-starter-monitor dependency.
The OpenTelemetry version should be <version>
In this case, you have to import the OpenTelemetry Bills of Materials
by following the OpenTelemetry documentation in the Spring Boot starter.
Step 2: Enable self-diagnostics
If something doesn't work as expected, you can enable self-diagnostics at the DEBUG level to get some insights. To do so, set the self-diagnostics level to ERROR, WARN, INFO, DEBUG, or TRACE by using the APPLICATIONINSIGHTS_SELF_DIAGNOSTICS_LEVEL environment variable.
To enable self-diagnostics at the DEBUG level when running a docker container, run the following command:
docker run -e APPLICATIONINSIGHTS_SELF_DIAGNOSTICS_LEVEL=DEBUG <image-name>
Note
Replace <image-name> with the docker image name accordingly.
Third-party information disclaimer
The third-party products that this article discusses are manufactured by companies that are independent of Microsoft. Microsoft makes no warranty, implied or otherwise, about the performance or reliability of these products.
Step 1: Enable diagnostic logging
Azure Monitor Exporter uses the OpenTelemetry API logger for internal logs. To enable the logger, run the following code snippet:
Step 2: Test connectivity between your application host and the ingestion service
Application Insights SDKs and agents send telemetry to get ingested as REST calls at our ingestion endpoints. To test connectivity from your web server or application host computer to the ingestion service endpoints, use cURL commands or raw REST requests from PowerShell. For more information, see Troubleshoot missing application telemetry in Azure Monitor Application Insights.
Known issues
The following items are known issues for the Azure Monitor OpenTelemetry Exporters:
The operation name is missing from dependency telemetry. The missing operation name causes failures and adversely affects performance tab experience.
The device model is missing from request and dependency telemetry. The missing device model adversely affects device cohort analysis.
The database server name is missing from the dependency name. Because the database server name isn't included, OpenTelemetry Exporters incorrectly aggregate tables that have the same name onto different servers.
Step 1: Enable diagnostic logging
The Microsoft Azure Monitor Exporter uses the Python standard logging library for its internal logging. OpenTelemetry API and Azure Monitor Exporter logs are assigned a severity level of WARNING or ERROR for irregular activity. The INFO severity level is used for regular or successful activity.
By default, the Python logging library sets the severity level to WARNING. Therefore, you must change the severity level to see logs under this severity setting. The following example code shows how to output logs of all severity levels to the console and a file:
Step 2: Test connectivity between your application host and the ingestion service
Application Insights SDKs and agents send telemetry to get ingested as REST calls at our ingestion endpoints. To test connectivity from your web server or application host computer to the ingestion service endpoints, use cURL commands or raw REST requests from PowerShell. For more information, see Troubleshoot missing application telemetry in Azure Monitor Application Insights.
Step 3: Avoid duplicate telemetry
Duplicate telemetry is often caused if you create multiple instances of processors or exporters. Make sure that you run only one exporter and processor at a time for each telemetry pillar (logs, metrics, and distributed tracing).
The following sections describe scenarios that can cause duplicate telemetry.
Duplicate trace logs in Azure Functions
If you see a pair of entries for each trace log within Application Insights, you probably enabled the following types of logging instrumentation:
The native logging instrumentation in Azure Functions
The azure-monitor-opentelemetry logging instrumentation within the distribution
To prevent duplication, you can disable the distribution's logging, but leave the native logging instrumentation in Azure Functions enabled. To do this, set the OTEL_LOGS_EXPORTER environment variable to None.
Duplicate telemetry in "Always On" Azure Functions
If the Always On setting in Azure Functions is set to On, Azure Functions keeps some processes running in the background after each run is complete. For instance, suppose that you have a five-minute timer function that calls configure_azure_monitor each time. After 20 minutes, you then might have four metric exporters that are running at the same time. This situation might be the source of your duplicate metrics telemetry.
In this situation, either set the Always On setting to Off, or try manually shutting down the providers between each configure_azure_monitor call. To shut down each provider, run shutdown calls for each current meter, tracer, and logger provider, as shown in the following code:
Azure Workbooks and Jupyter Notebooks might keep exporter processes running in the background. To prevent duplicate telemetry, clear the cache before you make more calls to configure_azure_monitor.
Step 4: Make sure that Flask request data is collected
If you implement a Flask application, you might find that you can't collect Requests table data from Application Insights while you use the Azure Monitor OpenTelemetry Distro client library for Python. This issue could occur if you don't structure your import declarations correctly. You might be importing the flask.Flask web application framework before you call the configure_azure_monitor function to instrument the Flask library. For example, the following code doesn't successfully instrument the Flask app:
from azure.monitor.opentelemetry import configure_azure_monitor
from flask import Flask
configure_azure_monitor()
app = Flask(__name__)
Instead, we recommend that you import the flask module as a whole, and then call configure_azure_monitor to configure OpenTelemetry to use Azure Monitor before you access flask.Flask:
from azure.monitor.opentelemetry import configure_azure_monitor
import flask
configure_azure_monitor()
app = flask.Flask(__name__)
Alternatively, you can call configure_azure_monitor before you import flask.Flask:
from azure.monitor.opentelemetry import configure_azure_monitor
configure_azure_monitor()
from flask import Flask
app = Flask(__name__)
Support
Select a tab for the language of your choice to discover support options.