README as published on PyPI with version 1.0.0b60.
Microsoft OpenTelemetry exporter for Azure Monitor
The exporter for Azure Monitor allows Python applications to export data from the OpenTelemetry SDK to Azure Monitor. The exporter is intended for users who require advanced configuration or have more complicated telemetry needs that require all of distributed tracing, logging and metrics. If you have simpler configuration requirements, we recommend using the Azure Monitor OpenTelemetry Distro instead for a simpler one-line setup.
Prior to using this SDK, please read and understand Data Collection Basics, especially the section on telemetry types. OpenTelemetry terminology differs from Application Insights terminology so it is important to understand the way the telemetry types map to each other.
Interaction with Azure monitor exporter starts with an instance of the AzureMonitorTraceExporter class for distributed tracing, AzureMonitorLogExporter for logging and AzureMonitorMetricExporter for metrics. You will need a connection_string to instantiate the object.
Please find the samples linked below for demonstration as to how to construct the exporter using a connection string.
Logging (experimental)
NOTE: The logging signal for the AzureMonitorLogExporter is currently in an EXPERIMENTAL state. Possible breaking changes may ensue in the future.
from azure.monitor.opentelemetry.exporter import AzureMonitorLogExporter
exporter = AzureMonitorLogExporter(
connection_string=os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"]
)
Metrics
from azure.monitor.opentelemetry.exporter import AzureMonitorMetricExporter
exporter = AzureMonitorMetricExporter(
connection_string=os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"]
)
Tracing
from azure.monitor.opentelemetry.exporter import AzureMonitorTraceExporter
exporter = AzureMonitorTraceExporter(
connection_string=os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"]
)
You can also instantiate the exporter directly via the constructor. In this case, the connection string will be automatically populated from the APPLICATIONINSIGHTS_CONNECTION_STRING environment variable.
from azure.monitor.opentelemetry.exporter import AzureMonitorLogExporter
exporter = AzureMonitorLogExporter()
from azure.monitor.opentelemetry.exporter import AzureMonitorMetricExporter
exporter = AzureMonitorMetricExporter()
from azure.monitor.opentelemetry.exporter import AzureMonitorTraceExporter
exporter = AzureMonitorTraceExporter()
Key concepts
Some of the key concepts for the Azure monitor exporter include:
OpenTelemetry: OpenTelemetry is a set of libraries used to collect and export telemetry data (metrics, logs, and traces) for analysis in order to understand your software's performance and behavior.
Instrumentation: The ability to call the OpenTelemetry API directly by any application is facilitated by instrumentation. A library that enables OpenTelemetry observability for another library is called an instrumentation Library.
Log: Log refers to capturing of logging, exception and events.
LogRecord: Represents a log record emitted from a supported logging library.
Logger: Converts a LogRecord into a readable LogData, and will be pushed through the SDK to be exported.
Logger Provider: Provides a Logger for the given instrumentation library.
LoggingHandler: A handler class which writes logging records in OpenTelemetry format from the standard Python logging library.
AzureMonitorLogExporter: This is the class that is initialized to send logging related telemetry to Azure Monitor.
Metric: Metric refers to recording raw measurements with predefined aggregation and sets of attributes for a period in time.
Measurement: Represents a data point recorded at a point in time.
Instrument: Instruments are used to report Measurements.
Meter: The Meter is responsible for creating Instruments.
Meter Provider: Provides a Meter for the given instrumentation library.
Metric Reader: An SDK implementation object that provides the common configurable aspects of the OpenTelemetry Metrics SDK such as collection, flushing and shutdown.
AzureMonitorMetricExporter: This is the class that is initialized to send metric related telemetry to Azure Monitor.
Trace: Trace refers to distributed tracing. A distributed trace is a set of events, triggered as a result of a single logical operation, consolidated across various components of an application. In particular, a Trace can be thought of as a directed acyclic graph (DAG) of Spans, where the edges between Spans are defined as parent/child relationship.
Span: Represents a single operation within a Trace. Can be nested to form a trace tree. Each trace contains a root span, which typically describes the entire operation and, optionally, one ore more sub-spans for its sub-operations.
Tracer Provider: Provides a Tracer for use by the given instrumentation library.
Span Processor: A span processor allows hooks for SDK's Span start and end method invocations. Follow the link for more information.
AzureMonitorTraceExporter: This is the class that is initialized to send tracing related telemetry to Azure Monitor.
Sampling: Sampling is a mechanism to control the noise and overhead introduced by OpenTelemetry by reducing the number of samples of traces collected and sent to the backend.
ApplicationInsightsSampler: Application Insights specific sampler used for consistent sampling across Application Insights SDKs and OpenTelemetry-based SDKs sending data to Application Insights. This sampler MUST be used whenever AzureMonitorTraceExporter is used.
All configuration options can be passed through the constructors of exporters through kwargs. Below is a list of configurable options.
connection_string: The connection string used for your Application Insights resource.
disable_offline_storage: Boolean value to determine whether to disable storing failed telemetry records for retry. Defaults to False.
storage_directory: Storage directory in which to store retry files. Defaults to <tempfile.gettempdir()>/Microsoft/AzureMonitor/opentelemetry-python-<your-instrumentation-key>.
credential: Token credential, such as ManagedIdentityCredential or ClientSecretCredential, used for Azure Active Directory (AAD) authentication. Defaults to None. See samples for examples. The credential will be automatically created from the APPLICATIONINSIGHTS_AUTHENTICATION_STRING environment variable if not explicitly passed in. See documentation for more.
Experimental features
Use the APPLICATIONINSIGHTS_EXPERIMENTAL_FEATURES environment variable to opt in to named experimental
features. Set it before constructing any exporter or calling configure_azure_monitor().
Separate multiple feature names with commas. Names are case-insensitive; surrounding whitespace is
ignored. Unset or empty values enable no experimental features. Unknown names are ignored with a warning.
The selection is shared across exporters in the same Python interpreter and cannot be changed after
the first exporter is constructed. Experimental features may change or be removed in future releases.
Multi-endpoint routing (preview)
Add multi_endpoint_routing to APPLICATIONINSIGHTS_EXPERIMENTAL_FEATURES before
constructing any exporter to route logs, spans, or metric data points using their
microsoft.instrumentation_key and microsoft.ingestion_endpoint
attributes. Both attributes are required; the endpoint must be HTTPS. Obtain
destinations from trusted, server-owned configuration, not request headers or baggage.
Invalid or missing destinations are dropped without falling back to the exporter's
connection string. With routing enabled, a host connection string is optional.
If supplied explicitly or through the environment, it is still parsed and validated
normally. Without host configuration, host retry storage, Statsbeat, and customer
SDK statistics are not initialized; destination-specific retry storage still works.
$env:APPLICATIONINSIGHTS_EXPERIMENTAL_FEATURES = "multi_endpoint_routing"
# To enable another experimental feature as well:
$env:APPLICATIONINSIGHTS_EXPERIMENTAL_FEATURES = "multi_endpoint_routing,gen_ai_input_output_limit_increase"
Routing is disabled unless explicitly selected in this list. The selection is
shared across log, trace, and metric exporters and is fixed at the first exporter
construction, as described under Experimental features.
Caller-supplied transports and scalar retry settings remain supported. Complete
custom pipelines and HTTPPolicy instances supplied through named, per-call, or
per-retry policy options are rejected because routing must construct an independent
policy chain for each destination. SansIOHTTPPolicy entries remain supported.
Routing attributes
Attribute
Required
Value
microsoft.instrumentation_key
Yes
Destination instrumentation key: a nonempty string, at most 200 characters before trimming.
microsoft.ingestion_endpoint
Yes
Absolute HTTPS ingestion endpoint, at most 2048 characters before trimming, without credentials, query, or fragment.
microsoft.ingestion_auth
No
"aad" selects Microsoft Entra authentication; other or missing values select key-only authentication.
microsoft.multi_endpoint_cloud_role
No
Cloud-role name; missing, blank, or non-string values use unknown_service.
Items are grouped by normalized endpoint and authentication mode. Set
microsoft.ingestion_auth to "aad" to use the exporter's configured credential;
the value is trimmed and case-insensitive. Other values use key-only authentication
and do not receive the exporter's token, even when a credential is configured.
AAD groups without a credential fail without being sent or stored; other groups
continue exporting.
Span events follow their parent span's destination, instrumentation key, and
authentication mode, not routing attributes on the events themselves.
Metrics use routing attributes on each data point, not the resource or
instrumentation scope. Points without valid routing attributes are dropped.
Cloud-role names come from the item's microsoft.multi_endpoint_cloud_role attribute;
missing, blank, or non-string values use unknown_service. Span events inherit their
parent span's role name. Cloud-role instances remain resource-derived.
Attach these attributes to each log record, each span, and each metric measurement
(for example, counter.add(1, attributes=destination)). Resource attributes, baggage,
and the current span do not automatically supply routing attributes to other
records or child spans. Span events are the exception: they inherit the parent
span's route. For observable metrics, set the attributes on each observation.
If a metric view filters attributes, retain the routing attributes.
Exporters in multi-endpoint routing mode drop application telemetry without valid
routing attributes instead of sending it to the host connection string.
This does not apply to Live Metrics: when enabled with a host connection string,
it can still show log and span samples in the host resource without routing
attributes. Statsbeat and customer SDK
statistics do not use per-item routing and are not copied to every destination;
their host-configuration requirements are described above.
Resources may share an ingestion endpoint while using different instrumentation
keys. They share a transport route within each exporter, but each telemetry item
retains its own key and cloud-role name. An existing
APPLICATIONINSIGHTS_CONNECTION_STRING is still parsed and validated; it is not
a fallback for items without routing attributes. When routing is disabled, the
exporter uses its normal single destination instead.
Microsoft Entra authentication
Pass a token credential, such as DefaultAzureCredential, through credential,
or configure managed identity using APPLICATIONINSIGHTS_AUTHENTICATION_STRING.
Set microsoft.ingestion_auth to "aad" on telemetry that requires Microsoft
Entra authentication, including resources with local authentication disabled.
Assign the identity the Monitoring Metrics Publisher role on each destination resource.
The default audience is Azure public cloud. For another cloud, set the audience
before constructing the exporter, for example:
All AAD destinations within an exporter share its credential and audience. Use
separately configured exporters when identities or clouds differ. The host connection
string's AadAudience does not apply to routed telemetry. Custom
authentication_policy is not supported in routing mode.
Security: Use only trusted routing destinations. Custom headers, policies,
hooks, transports, or sessions may send credentials to any routed destination,
including key-only routes.
Retry storage and recovery
Retry storage is separate from the host storage, partitioned by endpoint and
authentication mode, and shares the configured storage capacity across routed
partitions. Pending items preserve their original instrumentation keys and are
retried after a subsequent successful send to the same endpoint/authentication
group or by a shared background worker. The worker starts when the first
storage-backed route opens and checks opened routes every storage_maintenance_period
seconds (60 by default). It respects retry backoff, storage toggles, and rate limits,
and stops when the exporter shuts down. Stored destinations are not discovered at
startup; their route must be opened by new telemetry before background retries begin.
For destinations with enabled, available offline storage, retryable failures also
pause new transmissions to that endpoint/authentication group. New items are stored
until the retry window expires. The window uses the existing Retry-After handling,
or storage_min_retry_interval (60 seconds by default) when no valid delay is available.
Other destinations continue transmitting. This does not add .NET's exponential
backoff; export results retain the existing failure semantics.
Each exporter caches up to 64 endpoint/authentication routes. When storage is
enabled, those cached routes also receive offline-storage partitions. Different
keys using the same normalized endpoint and authentication mode share a route.
Additional destinations still transmit through short-lived clients without
offline persistence.
With offline storage enabled, the routed storage root admits a new partition only
while it contains fewer than 64 partition directories. Retained directories,
including empty directories from previous exporter lifetimes, count toward this
limit. Existing partitions can reopen at or above the limit, subject to the
client-cache limit. No partitions or pending batches are evicted to admit another
destination. New destinations at capacity use the same short-lived,
non-persisting overflow path; storage admission errors also use this path and log
an error. Admission is coordinated between exporters in the same process, not
across processes sharing a directory. Single-endpoint storage behavior is unchanged.
Delivery guarantees and limitations
Routing provides best-effort delivery, not a transactional or exactly-once
delivery guarantee:
Each destination group is attempted independently. One failed group does not
roll back successful groups. Export results describe the aggregate attempt,
not individual destination receipts; a failure can coexist with successful
delivery or persistence for other groups.
After configured HTTP retries, retryable items can be saved for later replay
only when offline storage is enabled and available. Non-retryable items are
not saved for replay. Storage disabled through configuration, unavailable
disk space or permissions, retention expiry, and capacity limits can cause loss.
Retried items can arrive more than once if the service accepted an earlier
request but its response was lost. Do not rely on global ordering across
destinations, batches, or retries.
Provider force_flush() requests processing of queued logs/spans or metric
collection and export. Completion does not confirm that every item was
ingested, nor does it drain all offline retry files.
Shut down providers before exiting so their processors and exporters can
finish pending work and stop background workers. Shutdown does not wait for
an unavailable destination to recover or guarantee that retry storage is empty.
Abrupt process termination can lose in-memory telemetry.
Treat local retry files as sensitive telemetry and restrict access to their
storage directory. For restart recovery and the route-cache limit, see
Retry storage and recovery.
Examples
Logging (experimental)
NOTE: The logging signal for the AzureMonitorLogExporter is currently in an EXPERIMENTAL state. Possible breaking changes may ensue in the future.
The following sections provide several code snippets covering some of the most common tasks, including:
When integrating the AzureMonitorLogExporter, it's strongly advised to utilize a named logger rather
than the root logger.
This recommendation stems from the exporter's dependency on azure-core for constructing and dispatching requests.
Since azure-core itself uses a Python logger, attaching the handler to the root logger would
inadvertently capture and export these internal log messages as well.
This triggers a recursive loop of logging and exporting, leading to an unnecessary proliferation of log data.
To avoid this, configure a named logger for your application's logging needs or set up your logging handler to filter out logs originating from the SDK library.
Export Hello World Log
"""
An example to show an application using Opentelemetry logging sdk. Logging calls to the standard Python
logging library are tracked and telemetry is exported to application insights with the AzureMonitorLogExporter.
"""
import os
import logging
from opentelemetry._logs import set_logger_provider
from opentelemetry.sdk._logs import LoggerProvider
from opentelemetry.instrumentation.logging.handler import LoggingHandler
from opentelemetry.sdk._logs.export import BatchLogRecordProcessor
from azure.monitor.opentelemetry.exporter import AzureMonitorLogExporter
logger_provider = LoggerProvider()
set_logger_provider(logger_provider)
exporter = AzureMonitorLogExporter(
connection_string=os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"]
)
logger_provider.add_log_record_processor(BatchLogRecordProcessor(exporter))
# Attach LoggingHandler to namespaced logger
handler = LoggingHandler()
logger = logging.getLogger(__name__)
logger.addHandler(handler)
logger.setLevel(logging.NOTSET)
logger.warning("Hello World!")
# Telemetry records are flushed automatically upon application exit
# If you would like to flush records manually yourself, you can call force_flush()
logger_provider.force_flush()
Export Correlated Log
"""
An example showing how to include context correlation information in logging telemetry.
"""
import os
import logging
from opentelemetry import trace
from opentelemetry._logs import set_logger_provider
from opentelemetry.sdk._logs import LoggerProvider
from opentelemetry.sdk._logs.export import BatchLogRecordProcessor
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.instrumentation.logging.handler import LoggingHandler
from azure.monitor.opentelemetry.exporter import AzureMonitorLogExporter
trace.set_tracer_provider(TracerProvider())
tracer = trace.get_tracer(__name__)
logger_provider = LoggerProvider()
set_logger_provider(logger_provider)
exporter = AzureMonitorLogExporter(
connection_string=os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"]
)
logger_provider.add_log_record_processor(BatchLogRecordProcessor(exporter))
# Attach LoggingHandler to namespaced logger
handler = LoggingHandler()
logger = logging.getLogger(__name__)
logger.addHandler(handler)
logger.setLevel(logging.NOTSET)
logger.info("INFO: Outside of span")
with tracer.start_as_current_span("foo"):
logger.warning("WARNING: Inside of span")
logger.error("ERROR: After span")
Export Custom Properties Log
"""
An example showing how to add custom properties to logging telemetry.
"""
import os
import logging
from opentelemetry._logs import set_logger_provider
from opentelemetry.sdk._logs import LoggerProvider
from opentelemetry.instrumentation.logging.handler import LoggingHandler
from opentelemetry.sdk._logs.export import BatchLogRecordProcessor
from azure.monitor.opentelemetry.exporter import AzureMonitorLogExporter
logger_provider = LoggerProvider()
set_logger_provider(logger_provider)
exporter = AzureMonitorLogExporter(
connection_string=os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"]
)
logger_provider.add_log_record_processor(BatchLogRecordProcessor(exporter))
# Attach LoggingHandler to namespaced logger
handler = LoggingHandler()
logger = logging.getLogger(__name__)
logger.addHandler(handler)
logger.setLevel(logging.NOTSET)
# Custom properties
logger.debug("DEBUG: Debug with properties", extra={"debug": "true"})
Export Exceptions Log
"""
An example showing how to export exception telemetry using the AzureMonitorLogExporter.
"""
import os
import logging
from opentelemetry._logs import (
get_logger_provider,
set_logger_provider,
)
from opentelemetry.sdk._logs import LoggerProvider
from opentelemetry.instrumentation.logging.handler import LoggingHandler
from opentelemetry.sdk._logs.export import BatchLogRecordProcessor
from azure.monitor.opentelemetry.exporter import AzureMonitorLogExporter
set_logger_provider(LoggerProvider())
exporter = AzureMonitorLogExporter(
connection_string=os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"]
)
get_logger_provider().add_log_record_processor(BatchLogRecordProcessor(exporter))
# Attach LoggingHandler to namespaced logger
handler = LoggingHandler()
logger = logging.getLogger(__name__)
logger.addHandler(handler)
logger.setLevel(logging.NOTSET)
# The following code will generate two pieces of exception telemetry
# that are identical in nature
try:
val = 1 / 0
print(val)
except ZeroDivisionError:
logger.exception("Error: Division by zero")
try:
val = 1 / 0
print(val)
except ZeroDivisionError:
logger.error("Error: Division by zero", stack_info=True, exc_info=True)
Metrics
The following sections provide several code snippets covering some of the most common tasks, including:
Review the OpenTelemetry Metrics SDK to learn how to use OpenTelemetry components to collect metrics.
Metric instrument usage
"""
An example to show an application using all instruments in the OpenTelemetry SDK. Metrics created
and recorded using the sdk are tracked and telemetry is exported to application insights with the
AzureMonitorMetricsExporter.
"""
import os
from typing import Iterable
from opentelemetry import metrics
from opentelemetry.metrics import CallbackOptions, Observation
from opentelemetry.sdk.metrics import MeterProvider
from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
from azure.monitor.opentelemetry.exporter import AzureMonitorMetricExporter
exporter = AzureMonitorMetricExporter(
connection_string=os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"]
)
reader = PeriodicExportingMetricReader(exporter, export_interval_millis=5000)
metrics.set_meter_provider(MeterProvider(metric_readers=[reader]))
# Create a namespaced meter
meter = metrics.get_meter_provider().get_meter("sample")
# Callback functions for observable instruments
def observable_counter_func(options: CallbackOptions) -> Iterable[Observation]:
yield Observation(1, {})
def observable_up_down_counter_func(
options: CallbackOptions,
) -> Iterable[Observation]:
yield Observation(-10, {})
def observable_gauge_func(options: CallbackOptions) -> Iterable[Observation]:
yield Observation(9, {})
# Counter
counter = meter.create_counter("counter")
counter.add(1)
# Async Counter
observable_counter = meter.create_observable_counter(
"observable_counter", [observable_counter_func]
)
# UpDownCounter
up_down_counter = meter.create_up_down_counter("up_down_counter")
up_down_counter.add(1)
up_down_counter.add(-5)
# Async UpDownCounter
observable_up_down_counter = meter.create_observable_up_down_counter(
"observable_up_down_counter", [observable_up_down_counter_func]
)
# Histogram
histogram = meter.create_histogram("histogram")
histogram.record(99.9)
# Async Gauge
gauge = meter.create_observable_gauge("gauge", [observable_gauge_func])
# Upon application exit, one last collection is made and telemetry records are
# flushed automatically. # If you would like to flush records manually yourself,
# you can call force_flush()
meter_provider.force_flush()
Metric custom views
"""
This example shows how to customize the metrics that are output by the SDK using Views. Metrics created
and recorded using the sdk are tracked and telemetry is exported to application insights with the
AzureMonitorMetricsExporter.
"""
import os
from opentelemetry import metrics
from opentelemetry.sdk.metrics import Counter, MeterProvider
from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
from opentelemetry.sdk.metrics.view import View
from azure.monitor.opentelemetry.exporter import AzureMonitorMetricExporter
exporter = AzureMonitorMetricExporter.from_connection_string(
os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"]
)
# Create a view matching the counter instrument `my.counter`
# and configure the new name `my.counter.total` for the result metrics stream
change_metric_name_view = View(
instrument_type=Counter,
instrument_name="my.counter",
name="my.counter.total",
)
reader = PeriodicExportingMetricReader(exporter, export_interval_millis=5000)
provider = MeterProvider(
metric_readers=[
reader,
],
views=[
change_metric_name_view,
],
)
metrics.set_meter_provider(provider)
meter = metrics.get_meter_provider().get_meter("view-name-change")
my_counter = meter.create_counter("my.counter")
my_counter.add(100)
More examples with the metrics Views SDK can be found here.
Metric record attributes
"""
An example to show an application using different attributes with instruments in the OpenTelemetry SDK.
Metrics created and recorded using the sdk are tracked and telemetry is exported to application insights
with the AzureMonitorMetricsExporter.
"""
import os
from opentelemetry import metrics
from opentelemetry.sdk.metrics import MeterProvider
from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
from azure.monitor.opentelemetry.exporter import AzureMonitorMetricExporter
exporter = AzureMonitorMetricExporter.from_connection_string(
os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"]
)
reader = PeriodicExportingMetricReader(exporter, export_interval_millis=5000)
metrics.set_meter_provider(MeterProvider(metric_readers=[reader]))
attribute_set1 = {
"key1": "val1"
}
attribute_set2 = {
"key2": "val2"
}
large_attribute_set = {}
for i in range(20):
key = "key{}".format(i)
val = "val{}".format(i)
large_attribute_set[key] = val
meter = metrics.get_meter_provider().get_meter("sample")
# Counter
counter = meter.create_counter("attr1_counter")
counter.add(1, attribute_set1)
# Counter2
counter2 = meter.create_counter("attr2_counter")
counter2.add(10, attribute_set1)
counter2.add(30, attribute_set2)
# Counter3
counter3 = meter.create_counter("large_attr_counter")
counter3.add(100, attribute_set1)
counter3.add(200, large_attribute_set)
Tracing
The following sections provide several code snippets covering some of the most common tasks, including:
"""
An example to show an application using Opentelemetry tracing api and sdk. Custom dependencies are
tracked via spans and telemetry is exported to application insights with the AzureMonitorTraceExporter.
"""
import os
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from azure.monitor.opentelemetry.exporter import AzureMonitorTraceExporter
tracer_provider = TracerProvider()
trace.set_tracer_provider(tracer_provider)
tracer = trace.get_tracer(__name__)
# This is the exporter that sends data to Application Insights
exporter = AzureMonitorTraceExporter(
connection_string=os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"]
)
span_processor = BatchSpanProcessor(exporter)
trace.get_tracer_provider().add_span_processor(span_processor)
with tracer.start_as_current_span("hello"):
print("Hello, World!")
# Telemetry records are flushed automatically upon application exit
# If you would like to flush records manually yourself, you can call force_flush()
tracer_provider.force_flush()
Instrumentation with requests library
OpenTelemetry also supports several instrumentations which allows to instrument with third party libraries.
For a list of instrumentations available in OpenTelemetry, visit the contrib documentation.
This example shows how to instrument with the requests library.
Install the requests instrumentation package using pip install opentelemetry-instrumentation-requests.
"""
An example to show an application instrumented with the OpenTelemetry requests instrumentation.
Calls made with the requests library will be automatically tracked and telemetry is exported to
application insights with the AzureMonitorTraceExporter.
See more info on the requests instrumentation here:
https://github.com/open-telemetry/opentelemetry-python-contrib/tree/main/instrumentation/opentelemetry-instrumentation-requests
"""
import os
import requests
from opentelemetry import trace
from opentelemetry.instrumentation.requests import RequestsInstrumentor
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from azure.monitor.opentelemetry.exporter import AzureMonitorTraceExporter
# This line causes your calls made with the requests library to be tracked.
RequestsInstrumentor().instrument()
trace.set_tracer_provider(TracerProvider())
tracer = trace.get_tracer(__name__)
exporter = AzureMonitorTraceExporter(
connection_string=os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"]
)
span_processor = BatchSpanProcessor(exporter)
trace.get_tracer_provider().add_span_processor(span_processor)
# This request will be traced
response = requests.get(url="https://azure.microsoft.com/")
Enabling sampling
You can enable sampling to limit the amount of telemetry records you receive. In order to enable correct sampling in Application Insights, use the ApplicationInsightsSampler as shown below.
"""
An example to show an application using the ApplicationInsightsSampler to enable sampling for your telemetry.
Specify a sampling rate for the sampler to limit the amount of telemetry records you receive. Custom dependencies
are tracked via spans and telemetry is exported to application insights with the AzureMonitorTraceExporter.
"""
import os
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from azure.monitor.opentelemetry.exporter import (
ApplicationInsightsSampler,
AzureMonitorTraceExporter,
)
# Sampler expects a sample rate of between 0 and 1 inclusive
# A rate of 0.75 means approximately 75% of your telemetry will be sent
sampler = ApplicationInsightsSampler(0.75)
trace.set_tracer_provider(TracerProvider(sampler=sampler))
tracer = trace.get_tracer(__name__)
exporter = AzureMonitorTraceExporter(
connection_string=os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"]
)
span_processor = BatchSpanProcessor(exporter)
trace.get_tracer_provider().add_span_processor(span_processor)
for i in range(100):
# Approximately 25% of these spans should be sampled out
with tracer.start_as_current_span("hello"):
print("Hello, World!")
Flush/shutdown behavior
For all applications set up with OpenTelemetry SDK and Azure Monitor exporters, telemetry is flushed automatically upon application exit. Note that this does not include when application ends abruptly or crashes due to uncaught exception.
Troubleshooting
The exporter raises exceptions defined in Azure Core.
Custom properties truncation
Span, span event, and log record attributes are exported as custom properties. Values are truncated to the following lengths (in characters):
Attributes
Max length
gen_ai.input.messages, gen_ai.output.messages
256 KiB (256 * 1024); 4 MiB (4 * 1024 * 1024) when the gen_ai_input_output_limit_increaseexperimental feature is enabled
When the gen_ai_input_output_limit_increase experimental feature is enabled, GenAI messages with multimodal content (for example, base64-encoded images or audio) can produce large telemetry items. If you capture such content, consider increasing the exporter timeout and storage_max_size settings, reducing the batch processor's max_export_batch_size, or bounding attribute size at the source with OTEL_ATTRIBUTE_VALUE_LENGTH_LIMIT.
Multi-endpoint routing
If routed telemetry is missing:
Confirm that multi_endpoint_routing was selected before the first exporter
was constructed. Changing the environment afterward does not change the
selection in that process.
Check the attributes on the actual log, span, or metric data point, not just
its resource or parent span. Missing or invalid destinations are dropped.
For Microsoft Entra destinations, check the "aad" marker, exporter
credential, audience, and destination role assignment.
Check exporter warnings/errors for authentication, storage, and route-capacity
failures. Enable DEBUG logging for azure.monitor.opentelemetry.exporter
to see invalid-routing-attribute diagnostics. Keep exporter diagnostics on a
console or separate handler rather than sending them back through the same
exporter.
If retry files remain after a restart, open their destination route with new
telemetry so background replay can resume. A successful provider flush is not
proof of ingestion; verify arrival in each destination resource.
Next steps
More sample code
Please find further examples in the samples directory demonstrating common scenarios.
Additional documentation
For more extensive documentation on the Azure Monitor service, see the Azure Monitor documentation on learn.microsoft.com.
For detailed overview of OpenTelemetry, visit their overview page.
For the official OpenTelemetry Python documentation and how to enable other telemetry scenarios, visit the official OpenTelemetry website.
For more information on the Azure Monitor OpenTelemetry Distro, which is a bundle of useful, pre-assembled components (one of them being this current package) that enable telemetry scenarios with Azure Monitor, visit the README.
Contributing
This project welcomes contributions and suggestions. Most contributions require you to agree to a
Contributor License Agreement (CLA) declaring that you have the right to, and actually do, grant us
the rights to use your contribution. For details, visit https://cla.microsoft.com.
When you submit a pull request, a CLA-bot will automatically determine whether you need to provide
a CLA and decorate the PR appropriately (e.g., label, comment). Simply follow the instructions
provided by the bot. You will only need to do this once across all repos using our CLA.