Rediger

Configure OpenTelemetry in Application Insights

Note

For .NET, Node.js, and Python applications:

For Java applications, use the Azure Monitor OpenTelemetry Distro.

For AI-assisted instrumentation guidance, see the Application Insights instrumentation skill. For guided setup and analysis of existing Application Insights instrumentation, see the Azure MCP Server tools for Azure Monitor.

This guide explains how to configure OpenTelemetry (OTel) in Azure Monitor Application Insights. For .NET, Node.js, and Python, use the Microsoft OpenTelemetry Distro. For Java, use the Azure Monitor OpenTelemetry Distro and its existing agent or native-image integrations.

First, enable OpenTelemetry for your language.

The Microsoft OpenTelemetry Distro package identifiers and install commands are:

Language Package Install command
Python microsoft-opentelemetry pip install microsoft-opentelemetry
Node.js @microsoft/opentelemetry npm install @microsoft/opentelemetry
.NET Microsoft.OpenTelemetry dotnet add package Microsoft.OpenTelemetry

Don't initialize the Microsoft OpenTelemetry Distro and Azure Monitor OpenTelemetry Distro together. Azure Monitor remains the telemetry destination; standalone Azure Monitor exporters retain their existing names.

The .NET examples use Microsoft.OpenTelemetry and OpenTelemetry namespaces. Initialize Node.js instrumentation before application libraries load. ESM applications must preload the Microsoft OpenTelemetry Distro loader. Set APPLICATIONINSIGHTS_CONNECTION_STRING before starting the application unless an example sets the connection string in code.

Note

For Azure Function Apps, see Use OpenTelemetry with Azure Functions.

Connection string

In Application Insights, a connection string defines the target location for sending telemetry data.

Use one of the following three ways to configure the connection string:

  • Configure UseMicrosoftOpenTelemetry() in Program.cs.

    // Import the Microsoft OpenTelemetry Distro and supporting APIs.
    using Microsoft.OpenTelemetry;
    
    // Create the application builder.
    var builder = WebApplication.CreateBuilder(args);
    
    // Configure the Microsoft OpenTelemetry Distro.
    builder.UseMicrosoftOpenTelemetry(options =>
    {
      options.Exporters = ExportTarget.AzureMonitor;
    
      // Set the connection string for Azure Monitor export.
      options.AzureMonitor.ConnectionString = "<ConnectionString>";
    });
    
    // Build the application with the configured telemetry services.
    var app = builder.Build();
    
    // Run the application and its telemetry providers.
    app.Run();
    
  • Set an environment variable.

    export APPLICATIONINSIGHTS_CONNECTION_STRING="<ConnectionString>"
    
  • Add the following section to appsettings.json, and then read it when initializing the distro.

        {
            "AzureMonitor": {
                "ConnectionString": "<ConnectionString>"
            }
        }
    
    // Import the Microsoft OpenTelemetry Distro and supporting APIs.
    using Microsoft.OpenTelemetry;
    
    // Create the application builder.
    var builder = WebApplication.CreateBuilder(args);
    
    // Configure the Microsoft OpenTelemetry Distro.
    builder.UseMicrosoftOpenTelemetry(options =>
    {
      options.Exporters = ExportTarget.AzureMonitor;
    
      // Read the environment setting before the application configuration.
      options.AzureMonitor.ConnectionString =
        builder.Configuration["APPLICATIONINSIGHTS_CONNECTION_STRING"] ??
        builder.Configuration["AzureMonitor:ConnectionString"];
    });
    
    // Build the application with the configured telemetry services.
    var app = builder.Build();
    
    // Run the application and its telemetry providers.
    app.Run();
    

Note

An explicit options.AzureMonitor.ConnectionString value takes precedence. The configuration-file example checks the environment-variable key before the AzureMonitor section. Reading the section explicitly avoids relying on implicit configuration binding.

Set the Cloud Role Name and the Cloud Role Instance

The Microsoft OpenTelemetry Distro for .NET, Node.js, and Python, and Azure Monitor OpenTelemetry for Java, detect resource context where supported and provide default values for the Cloud Role Name and Cloud Role Instance. You can override those values for your application. The cloud role name appears on the Application Map as the name under a node.

Set the Cloud Role Name and the Cloud Role Instance through Resource attributes. Cloud Role Name uses service.namespace and service.name attributes, but 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 the Cloud Role Name and the Cloud Role Instance
// Import the Microsoft OpenTelemetry Distro and supporting APIs.
using Microsoft.OpenTelemetry;
using OpenTelemetry;
using OpenTelemetry.Resources;

// Define the service attributes used for cloud role name and instance.
var resourceAttributes = new Dictionary<string, object>
{
    ["service.name"] = "<ServiceName>",
    ["service.namespace"] = "<ServiceNamespace>",
    ["service.instance.id"] = "<ServiceInstanceId>"
};

// Create the application builder.
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddOpenTelemetry()

  // Configure the Microsoft OpenTelemetry Distro.
  .UseMicrosoftOpenTelemetry(options =>
  {
    options.Exporters = ExportTarget.AzureMonitor;
  })

    // Apply the resource attributes to traces, metrics, and logs.
    .ConfigureResource(resourceBuilder => resourceBuilder.AddAttributes(
        resourceAttributes));

// Build the application with the configured telemetry services.
var app = builder.Build();

// Run the application and its telemetry providers.
app.Run();

Set resource attributes

The Microsoft OpenTelemetry Distro for .NET, Node.js, and Python, and Azure Monitor OpenTelemetry for Java, enable resource detection in supported Azure environments. For more information, see Automatic data collection and resource detectors.

For manual setups, set resource attributes directly by using standard OpenTelemetry options:

# Set variables
serviceName="<ServiceName>"
location="<Location>"
subscriptionId="<SubscriptionId>"
resourceGroupName="<ResourceGroupName>"
appName="<AppName>"

# Build App Service resource ID
path="/subscriptions/$subscriptionId/resourceGroups/$resourceGroupName"
provider="/providers/Microsoft.Web/sites/$appName"
resourceId="$path$provider"

resourceAttributes="cloud.provider=azure,cloud.region=$location"
resourceAttributes+=",cloud.resource_id=$resourceId"
export OTEL_SERVICE_NAME="$serviceName"
export OTEL_RESOURCE_ATTRIBUTES="$resourceAttributes"

On Windows PowerShell:

# Set variables
$serviceName = "<ServiceName>"
$location = "<Location>"
$subscriptionId = "<SubscriptionId>"
$resourceGroupName = "<ResourceGroupName>"
$appName = "<AppName>"

# Build App Service resource ID
$path = "/subscriptions/$subscriptionId/resourceGroups/$resourceGroupName"
$provider = "/providers/Microsoft.Web/sites/$appName"
$resourceId = "$path$provider"

$resourceAttributes = "cloud.provider=azure,cloud.region=$location"
$resourceAttributes += ",cloud.resource_id=$resourceId"
$env:OTEL_SERVICE_NAME = $serviceName
$env:OTEL_RESOURCE_ATTRIBUTES = $resourceAttributes

Enable sampling

Sampling reduces telemetry ingestion volume and cost. The distros support fixed-percentage and rate-limited sampling for Azure Monitor export. You can also align application logs with trace sampling decisions. The sampler attaches sampling information to exported spans so Application Insights can adjust experience counts. For a conceptual overview, see Learn more about sampling.

Important

  • Sampling decisions apply to traces (spans).
  • Logs can follow trace sampling decisions. This behavior is enabled by default in the Microsoft OpenTelemetry Distro for .NET and disabled by default in the Node.js and Python versions of the Microsoft OpenTelemetry Distro. See trace-based sampling for logs.
  • Metrics are never sampled.

Note

If you see unexpected charges or high costs in Application Insights, common causes include high telemetry volume, data ingestion spikes, and misconfigured sampling. To start troubleshooting, see Troubleshoot high data ingestion in Application Insights.

Configure sampling by using environment variables

Use standard OpenTelemetry environment variables to select the sampler and provide its argument where your distro reads them. Choose one configuration method; you don't need to configure the same sampling settings in both code and environment variables. Follow the version-specific guidance in the .NET tabs. For more information about sampler names, see OTEL_TRACES_SAMPLER.

For Microsoft.OpenTelemetry 1.1.0, use the code examples to set sampling in UseMicrosoftOpenTelemetry(). You don't also need to set OTEL_TRACES_SAMPLER or OTEL_TRACES_SAMPLER_ARG.

The following examples set the sampling environment variables for Node.js and Python. For the .NET version covered in the preceding tabs, use code-based configuration instead.

Note

The following examples aren't valid for Java. For the correct environment variables, see the previous Java tab.

Fixed-percentage sampling (~10%)

export OTEL_TRACES_SAMPLER="microsoft.fixed_percentage"
export OTEL_TRACES_SAMPLER_ARG=0.1

Rate-limited sampling (~1.5 traces/sec)

export OTEL_TRACES_SAMPLER="microsoft.rate_limited"
export OTEL_TRACES_SAMPLER_ARG=1.5

Configure sampling in code

Note

Sampler configuration and precedence depend on the language. The .NET examples set distro options explicitly. Python uses the sampler environment variables. For Node.js, avoid conflicting settings in code and the environment.

Fixed percentage sampling

// Import the Microsoft OpenTelemetry Distro and supporting APIs.
using Microsoft.OpenTelemetry;

// Create the application builder.
var builder = WebApplication.CreateBuilder(args);

// Configure the Microsoft OpenTelemetry Distro.
builder.UseMicrosoftOpenTelemetry(options =>
{
  options.Exporters = ExportTarget.AzureMonitor;

  // Select fixed-percentage sampling instead of rate-limited sampling.
  options.AzureMonitor.TracesPerSecond = null;

  // Keep approximately 10% of traces.
  options.AzureMonitor.SamplingRatio = 0.1F;
});

// Build the application with the configured telemetry services.
var app = builder.Build();

// Run the application and its telemetry providers.
app.Run();

Rate-limited sampling

// Import the Microsoft OpenTelemetry Distro and supporting APIs.
using Microsoft.OpenTelemetry;

// Create the application builder.
var builder = WebApplication.CreateBuilder(args);

// Configure the Microsoft OpenTelemetry Distro.
builder.UseMicrosoftOpenTelemetry(options =>
{
  options.Exporters = ExportTarget.AzureMonitor;

  // Limit sampling to approximately 1.5 traces per second.
  options.AzureMonitor.TracesPerSecond = 1.5;
});

// Build the application with the configured telemetry services.
var app = builder.Build();

// Run the application and its telemetry providers.
app.Run();

Note

The Microsoft OpenTelemetry Distro for .NET defaults to rate-limited sampling at five traces per second. Set TracesPerSecond to null when selecting fixed-percentage sampling in code.

Tip

When using fixed-percentage sampling and you're not sure what value to set for the sampling rate, start at 5% (0.05). Adjust the rate based on the accuracy of the operations shown in the failures and performance panes. Any sampling reduces accuracy, so alert on OpenTelemetry metrics, which are unaffected by sampling.

Configure sampling in the configuration file

Read your sampling settings from builder.Configuration and assign them to options.AzureMonitor.SamplingRatio or options.AzureMonitor.TracesPerSecond when initializing the Microsoft OpenTelemetry Distro. If you select percentage sampling, also set TracesPerSecond = null. Validate ratios from 0 through 1 and nonnegative rate limits. You don't also need sampler environment variables for this configuration.

Configure trace-based sampling for logs

When you enable this feature, the system drops log records that belong to unsampled traces so your logs stay aligned with trace sampling.

  • A log record is part of a trace when it has a valid SpanId.
  • If the associated trace's TraceFlags indicate not sampled, the feature drops the log record.
  • Log records without any trace context aren't affected.
  • The default depends on the language and distro version. See the per-language settings that follow.

Use the following settings to configure trace-based log sampling:

The distro enables trace-based log sampling by default. Set EnableTraceBasedLogsSampler to false to disable it.

// Configure the Microsoft OpenTelemetry Distro.
builder.Services.AddOpenTelemetry().UseMicrosoftOpenTelemetry(options =>
{
  options.Exporters = ExportTarget.AzureMonitor;
});

Live metrics

Live metrics provides a real-time analytics dashboard for insight into application activity and performance.

Important

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.

This feature is enabled by default.

You can disable Live Metrics when you configure the Microsoft OpenTelemetry Distro.

// Configure the Microsoft OpenTelemetry Distro.
builder.Services.AddOpenTelemetry().UseMicrosoftOpenTelemetry(options =>
{
  options.Exporters = ExportTarget.AzureMonitor;

  // Disable Live Metrics.
  options.AzureMonitor.EnableLiveMetrics = false;
});

Enable Microsoft Entra ID (formerly Azure AD) authentication

To create a more secure connection to Azure, enable Microsoft Entra authentication. This authentication method prevents unauthorized telemetry from being ingested into your subscription.

For more information, see the dedicated Microsoft Entra authentication page linked for each supported language.

For information on configuring Entra ID authentication, see Microsoft Entra authentication for Application Insights.

For the Microsoft OpenTelemetry Distro, set options.AzureMonitor.Credential. See the .NET authentication example.

Offline storage and automatic retries

Azure Monitor OpenTelemetry-based offerings cache telemetry when an application disconnects from Application Insights and retry sending for up to 48 hours. For data handling recommendations, see Export and delete private data. High-load applications occasionally drop telemetry for two reasons: exceeding the allowable time or exceeding the maximum file size. When necessary, the product prioritizes recent events over old ones.

The Microsoft OpenTelemetry Distro 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, set options.AzureMonitor.StorageDirectory when configuring the Microsoft OpenTelemetry Distro.

// Import the Microsoft OpenTelemetry Distro and supporting APIs.
using Microsoft.OpenTelemetry;

// Create the application builder.
var builder = WebApplication.CreateBuilder(args);

// Configure the Microsoft OpenTelemetry Distro.
builder.UseMicrosoftOpenTelemetry(options =>
{
  options.Exporters = ExportTarget.AzureMonitor;

    // Store telemetry here when the exporter cannot send it immediately.
    options.AzureMonitor.StorageDirectory = "<StorageDirectory>";
});

// Build the application with the configured telemetry services.
var app = builder.Build();

// Run the application and its telemetry providers.
app.Run();

To disable this feature, set options.AzureMonitor.DisableOfflineStorage = 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. Microsoft doesn't officially support the OTLP Exporter or any components or third-party experiences downstream of it.

The Microsoft OpenTelemetry Distro includes OTLP export. Configure your collector endpoint with OTEL_EXPORTER_OTLP_ENDPOINT, and select both destinations:

// Import the Microsoft OpenTelemetry Distro and supporting APIs.
using Microsoft.OpenTelemetry;

// Create the application builder.
var builder = WebApplication.CreateBuilder(args);

// Configure the Microsoft OpenTelemetry Distro.
builder.UseMicrosoftOpenTelemetry(options =>
{
  // Send telemetry to Azure Monitor and the configured OTLP collector.
  options.Exporters = ExportTarget.AzureMonitor | ExportTarget.Otlp;
});

// Build the application with the configured telemetry services.
var app = builder.Build();

// Run the application and its telemetry providers.
app.Run();

OpenTelemetry configurations

You can configure the following settings through environment variables. Use the tab for your language and distro.

Environment variable Description
APPLICATIONINSIGHTS_CONNECTION_STRING Set this variable to the connection string for your Application Insights resource.
APPLICATIONINSIGHTS_STATSBEAT_DISABLED Set this variable to true to opt out of internal metrics collection.
OTEL_RESOURCE_ATTRIBUTES Key-value pairs to use 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, OTEL_SERVICE_NAME takes precedence.

Redact URL query strings

To redact URL query strings, turn off query string collection. This setting is recommended if you call Azure storage by using a SAS token.

The Microsoft.OpenTelemetry distro includes ASP.NET Core and HttpClient instrumentation. For applications that handle sensitive query strings, explicitly enable query redaction before initializing the distro:

  • Set OTEL_DOTNET_EXPERIMENTAL_ASPNETCORE_DISABLE_URL_QUERY_REDACTION to false for ASP.NET Core instrumentation.
  • Set OTEL_DOTNET_EXPERIMENTAL_HTTPCLIENT_DISABLE_URL_QUERY_REDACTION to false for HttpClient instrumentation.

Setting either variable to true disables that instrumentation's query-string redaction.

Metric export interval

You can configure the metric export interval by using the OTEL_METRIC_EXPORT_INTERVAL environment variable.

export OTEL_METRIC_EXPORT_INTERVAL="60000"

The default value is 60000 milliseconds (60 seconds). This setting controls how often the OpenTelemetry SDK exports metrics.

Tip

Azure Monitor Metrics and Azure Monitor Workspace ingest custom metrics at a fixed 60-second interval. Metrics sent more frequently are buffered and processed once every 60 seconds. Log Analytics records metrics at the interval they’re sent, which can increase cost at shorter intervals and delay visibility at longer ones.

For reference, see the following OpenTelemetry specifications:

Troubleshooting, feedback, and support

Tip

The following sections are available across all OpenTelemetry Distro articles.

Troubleshooting

OpenTelemetry Feedback

To provide feedback:

Support

Select a tab for the language of your choice to discover support options.

Next steps