Edit

Share via


Configure Azure Monitor OpenTelemetry

This guide explains how to configure OpenTelemetry (OTel) in Azure Monitor Application Insights using the Azure Monitor OpenTelemetry distro. Proper configuration ensures consistent telemetry data collection across .NET, Java, Node.js, and Python applications, allowing for more reliable monitoring and diagnostics.

Note

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

Connection string

A connection string in Application Insights defines the target location for sending telemetry data.

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();
  • Set an environment variable.
   APPLICATIONINSIGHTS_CONNECTION_STRING=<Your Connection String>
  • Add the following section to your appsettings.json config file.
  {
    "AzureMonitor": {
        "ConnectionString": "<Your Connection String>"
    }
  }

Note

If you set the connection string in more than one place, we adhere to the following precedence:

  1. Code
  2. Environment Variable
  3. Configuration File

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(resourceAttributes));

// Build the ASP.NET Core web application.
var app = builder.Build();

// Start the ASP.NET Core web application.
app.Run();

Enable Sampling

Sampling reduces telemetry ingestion volume and cost. Azure Monitor’s OpenTelemetry distro supports two sampling strategies for traces and (optionally) lets you align application logs to your trace sampling decisions. The sampler attaches the selected sampling ratio or rate to exported spans so Application Insights can adjust experience counts accurately. For a conceptual overview, see Learn more about sampling.

Important

Scope of sampling

  • Sampling decisions apply to traces (spans).
  • Metrics are never sampled.
  • Logs are not sampled by default. You can opt in to trace‑based sampling for logs so that logs that belong to unsampled traces are dropped (details below).

Note

If you're seeing 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

Use standard OpenTelemetry environment variables to select the sampler and provide its argument:

  • OTEL_TRACES_SAMPLER — sampler type
    • microsoft.fixed.percentage — sample a fraction of traces.
    • microsoft.rate_limited — cap traces per second.
  • OTEL_TRACES_SAMPLER_ARG — sampler argument
    • For microsoft.fixed.percentage: value in 0.0–1.0 (for example, 0.1 = ~10%).
    • For microsoft.rate_limited: maximum traces per second (for example, 1.5).

Examples

# Fixed percentage (~10%)
export OTEL_TRACES_SAMPLER="microsoft.fixed.percentage"
export OTEL_TRACES_SAMPLER_ARG=0.1

# Rate-limited (~1.5 traces/sec)
export OTEL_TRACES_SAMPLER="microsoft.rate_limited"
export OTEL_TRACES_SAMPLER_ARG=1.5

Note

When both code-level options and environment variables are configured, environment variables take precedence. Default sampler behavior can differ by language—see the tabs.

Trace‑based sampling for logs

When enabled, log records that belong to unsampled traces are dropped so that your logs remain aligned with trace sampling.

Behavior

  • A log record is considered part of a trace when it has a valid SpanId.
  • If the associated trace’s TraceFlags indicate not sampled, the log record is dropped.
  • Log records without any trace context are not affected.
  • The feature is disabled by default. Enablement is language-specific—see the tabs.

You can configure sampling in code or by using the environment variables shown above.

Configure in code

Fixed percentage

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddOpenTelemetry().UseAzureMonitor(o =>
{
    o.SamplingRatio = 0.1F; // ~10%
});
var app = builder.Build();
app.Run();

Rate-limited

var builder = WebApplication.CreateBuilder(args);
builder.Services.AddOpenTelemetry().UseAzureMonitor(o =>
{
    o.TracesPerSecond = 1.5; // ~1.5 traces/sec
});
var app = builder.Build();
app.Run();

Note

If you do not set a sampler in code or through environment variables, Azure Monitor uses ApplicationInsightsSampler by default.

Trace‑based sampling for logs

builder.Services.AddOpenTelemetry().UseAzureMonitor(o =>
{
    o.EnableTraceBasedLogsSampler = true;
});

Tip

When using fixed‑percentage sampling and you aren't sure what to set the sampling rate as, 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 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.

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.

Users can disable Live Metrics when configuring the Distro.

builder.Services.AddOpenTelemetry().UseAzureMonitor(options => {
	// Disable the Live Metrics feature.
    options.EnableLiveMetrics = false;
});

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.

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

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

Offline Storage and Automatic Retries

Azure Monitor OpenTelemetry-based offerings cache telemetry when an application disconnects from Application Insights and retries 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 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.

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.

  1. Install the OpenTelemetry.Exporter.OpenTelemetryProtocol package in your project.
    dotnet add package OpenTelemetry.Exporter.OpenTelemetryProtocol
  1. 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();

OpenTelemetry configurations

The following OpenTelemetry configurations can be accessed through environment variables while using the Azure Monitor OpenTelemetry Distros.

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.

Redact URL Query Strings

To redact URL query strings, turn off query string collection. We recommend this setting if you call Azure storage using a SAS token.

When you're using the Azure.Monitor.OpenTelemetry.AspNetCore distro package, both the ASP.NET Core and HttpClient Instrumentation libraries are included. Our distro package sets Query String Redaction off by default.

To change this behavior, you must set an environment variable to either true or false.

  • ASP.NET Core Instrumentation: OTEL_DOTNET_EXPERIMENTAL_ASPNETCORE_DISABLE_URL_QUERY_REDACTION Query String Redaction is disabled by default. To enable, set this environment variable to false.
  • Http Client Instrumentation: OTEL_DOTNET_EXPERIMENTAL_HTTPCLIENT_DISABLE_URL_QUERY_REDACTION Query String Redaction is disabled by default. To enable, set this environment variable to false.

Metric export interval

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

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: