Azure Monitor OpenTelemetry Exporter

raw JSON →
1.0.0b49 verified Tue May 12 auth: no python install: verified

The Azure Monitor OpenTelemetry Exporter for Python enables applications to send telemetry data (traces, metrics, and logs) from the OpenTelemetry SDK to Azure Monitor Application Insights. It is designed for users requiring advanced configuration and fine-grained control over their telemetry pipeline. This library is part of the Azure SDK for Python and is currently in a beta release phase, receiving frequent updates and improvements.

pip install azure-monitor-opentelemetry-exporter --pre
error ImportError: cannot import name 'LogData' from 'opentelemetry.sdk._logs'
cause This error occurs due to an incompatibility between the installed version of `azure-monitor-opentelemetry-exporter` and the `opentelemetry-sdk`. The `LogData` class or related internal modules were moved or removed in newer versions of `opentelemetry-sdk` (e.g., >=1.41.0), which breaks the import in older exporter versions.
fix
Ensure that your azure-monitor-opentelemetry-exporter and opentelemetry-sdk versions are compatible. It is recommended to update azure-monitor-opentelemetry-exporter to its latest version, which typically has tighter dependency pins to avoid such conflicts. Alternatively, if forced to use an older exporter, you might need to pin opentelemetry-sdk to a compatible version (e.g., pip install opentelemetry-sdk==1.39.0).
error ValueError: Instrumentation key cannot be none or empty.
cause This error indicates that the exporter was initialized without a valid Azure Application Insights connection string or instrumentation key, which is essential for sending telemetry data.
fix
Provide a valid connection string to the exporter, either directly in the constructor, via the APPLICATIONINSIGHTS_CONNECTION_STRING environment variable, or by using the from_connection_string class method. For example: exporter = AzureMonitorTraceExporter(connection_string='InstrumentationKey=YOUR_INSTRUMENTATION_KEY') or by setting the environment variable export APPLICATIONINSIGHTS_CONNECTION_STRING='InstrumentationKey=YOUR_INSTRUMENTATION_KEY' before running your application.
error Telemetry not appearing in Azure Monitor Application Insights.
cause This is a common symptom that can stem from several issues, including an incorrect or missing connection string, network connectivity problems to Azure ingestion endpoints, incompatible OpenTelemetry SDK versions, or incorrect setup of span/metric/log processors and exporters within your application.
fix
First, verify the APPLICATIONINSIGHTS_CONNECTION_STRING is correctly set and valid. Second, enable diagnostic logging for the exporter (logging.getLogger('azure.monitor.opentelemetry.exporter').setLevel(logging.DEBUG)) to check for any errors during export. Third, confirm network connectivity to Azure ingestion endpoints. Finally, ensure all OpenTelemetry components (TracerProvider, MeterProvider, LoggerProvider, and their respective processors and exporters) are correctly initialized and that the exporter instance is added to the relevant providers.
error AttributeError: 'ProxyTracerProvider' object has no attribute 'resource'
cause This specific `AttributeError` can occur when using the `configure_azure_monitor` helper function alongside an OpenTelemetry SDK setup that results in a `ProxyTracerProvider` not having the expected `resource` attribute, often due to version mismatches or an unconventional initialization order.
fix
Downgrading azure-monitor-opentelemetry-exporter to an earlier stable version (e.g., 1.0.0b28) or azure-monitor-opentelemetry to 1.6.1 has been reported as a workaround. A more robust solution involves explicitly creating and configuring your own TracerProvider with a Resource instance, rather than relying solely on configure_azure_monitor if it's causing conflicts.
breaking The package name has undergone several changes. Ensure you are using the correct and current package name: `azure-monitor-opentelemetry-exporter`. Older documentation or samples might refer to `azure-opentelemetry-exporter-azuremonitor` or `microsoft-opentelemetry-exporter-azuremonitor`.
fix Always use `pip install azure-monitor-opentelemetry-exporter --pre` and import from `azure.monitor.opentelemetry.exporter`.
deprecated The `AzureMonitorLogExporter` for logging is currently in an EXPERIMENTAL state. Microsoft warns that possible breaking changes may occur in future releases for this component.
fix Be aware that logging implementation might require adjustments with future updates. Review the changelog for specific breaking changes in logging.
gotcha Users often confuse this exporter with the `Azure Monitor OpenTelemetry Distro`. This `azure-monitor-opentelemetry-exporter` library is for advanced scenarios requiring explicit OpenTelemetry SDK configuration. For simpler, one-line setup and auto-instrumentation, the `azure-monitor-opentelemetry` distro is recommended.
gotcha Connection string is the primary configuration method. It's best practice to set the `APPLICATIONINSIGHTS_CONNECTION_STRING` environment variable for authentication. Directly embedding the instrumentation key in code is not recommended for production.
gotcha Failing to explicitly shut down or flush OpenTelemetry providers and exporters can lead to lost telemetry. It is critical to call `shutdown()` on `TracerProvider`, `MeterProvider`, and `LoggerProvider` before your application exits to ensure all buffered telemetry is sent.
gotcha When logging in Azure Functions environments, avoid duplicate telemetry by not enabling both the native logging instrumentation in Azure Functions and the `azure-monitor-opentelemetry` logging instrumentation within the distribution. This can result in two entries for each log.
gotcha The Azure Monitor Exporter currently has limitations in handling oversized log messages (exceeding 65536 bytes), which may prevent larger logs from being delivered to Application Insights. This could be a blocker for migration in environments with verbose logging.
fix Be mindful of log message size; there is no current workaround to guarantee delivery of oversized logs. Monitor related GitHub issues for updates.
breaking The instrumentation key provided within the connection string must be a valid UUID. Failing to provide a properly formatted UUID will result in a `ValueError` during exporter initialization.
fix Ensure the `InstrumentationKey` parameter in your connection string (or the environment variable `APPLICATIONINSIGHTS_CONNECTION_STRING`) is set to a valid UUID.
gotcha The instrumentation key, typically found within the connection string, must be a valid UUID (Globally Unique Identifier). Providing an incorrectly formatted instrumentation key will result in a `ValueError` during exporter initialization.
fix Ensure your `APPLICATIONINSIGHTS_CONNECTION_STRING` environment variable or the `connection_string` parameter in the exporter constructor contains an instrumentation key that adheres to the UUID format (e.g., `xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx`).
python os / libc status wheel install import disk
3.10 alpine (musl) wheel - 1.71s 51.5M
3.10 alpine (musl) - - 1.61s 50.3M
3.10 slim (glibc) wheel 4.9s 1.30s 52M
3.10 slim (glibc) - - 1.25s 51M
3.11 alpine (musl) wheel - 2.16s 55.9M
3.11 alpine (musl) - - 2.30s 54.7M
3.11 slim (glibc) wheel 4.8s 1.92s 56M
3.11 slim (glibc) - - 1.79s 55M
3.12 alpine (musl) wheel - 2.20s 47.1M
3.12 alpine (musl) - - 2.23s 46.0M
3.12 slim (glibc) wheel 4.2s 2.19s 48M
3.12 slim (glibc) - - 2.13s 46M
3.13 alpine (musl) wheel - 1.90s 46.9M
3.13 alpine (musl) - - 1.81s 45.6M
3.13 slim (glibc) wheel 4.2s 1.84s 47M
3.13 slim (glibc) - - 1.92s 46M
3.9 alpine (musl) wheel - 1.64s 51.4M
3.9 alpine (musl) - - 1.53s 50.4M
3.9 slim (glibc) wheel 5.8s 1.55s 52M
3.9 slim (glibc) - - 1.35s 51M

This quickstart demonstrates how to set up OpenTelemetry tracing, metrics, and logging with the Azure Monitor Exporter. It uses a connection string, preferably from an environment variable (`APPLICATIONINSIGHTS_CONNECTION_STRING`), to authenticate and send telemetry to Azure Application Insights. Remember to replace 'YOUR_INSTRUMENTATION_KEY' with your actual key if not using an environment variable. Ensure to call `shutdown()` on providers to guarantee telemetry is flushed before the application exits.

import os
import logging
from opentelemetry import trace, metrics
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry.sdk.metrics import MeterProvider
from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader, ConsoleMetricExporter
from opentelemetry._logs import set_logger_provider
from opentelemetry.sdk._logs import LoggerProvider, LoggingHandler
from opentelemetry.sdk._logs.export import BatchLogRecordProcessor
from azure.monitor.opentelemetry.exporter import (
    AzureMonitorTraceExporter,
    AzureMonitorMetricExporter,
    AzureMonitorLogExporter
)

CONNECTION_STRING = os.environ.get('APPLICATIONINSIGHTS_CONNECTION_STRING', 'InstrumentationKey=YOUR_INSTRUMENTATION_KEY')

# --- Tracing --- 
print('Setting up tracing...')
exporter_trace = AzureMonitorTraceExporter(connection_string=CONNECTION_STRING)
tracer_provider = TracerProvider()
tracer_provider.add_span_processor(BatchSpanProcessor(exporter_trace))
trace.set_tracer_provider(tracer_provider)
tracer = trace.get_tracer(__name__)

with tracer.start_as_current_span("my-trace-span"):
    print("Hello from trace!")

# --- Metrics ---
print('Setting up metrics...')
exporter_metric = AzureMonitorMetricExporter(connection_string=CONNECTION_STRING)
metric_reader = PeriodicExportingMetricReader(exporter_metric, export_interval_millis=1000)
meter_provider = MeterProvider(metric_readers=[metric_reader])
metrics.set_meter_provider(meter_provider)
meter = metrics.get_meter(__name__)

counter = meter.create_counter("my_counter", description="A simple counter")
counter.add(1, {"key": "value"})

# --- Logging ---
print('Setting up logging...')
exporter_log = AzureMonitorLogExporter(connection_string=CONNECTION_STRING)
logger_provider = LoggerProvider()
set_logger_provider(logger_provider)
logger_provider.add_log_record_processor(BatchLogRecordProcessor(exporter_log))
handler = LoggingHandler(logger_provider=logger_provider)

# Attach OTel handler to root logger
root_logger = logging.getLogger()
root_logger.addHandler(handler)
root_logger.setLevel(logging.INFO)

# Log a message
root_logger.info("Hello from log!")

# --- Flush and Shutdown ---
print('Flushing and shutting down...')
tracer_provider.shutdown()
meter_provider.shutdown()
logger_provider.shutdown()

print('Telemetry sent to Azure Monitor (check your Application Insights resource).')