OpenCensus Azure Monitor Exporter
OpenCensus Azure Monitor Exporter is a Python library that enables applications to export telemetry data (traces, metrics, and logs) to Azure Monitor and Application Insights. It's part of the OpenCensus project, which is currently in maintenance mode, with OpenTelemetry being the recommended successor for new development. The library receives critical bug fixes but no new feature development. The current version is 1.1.15.
Common errors
-
ModuleNotFoundError: No module named 'opencensus-ext-azure'
cause The 'opencensus-ext-azure' package, or its base 'opencensus' package, is not installed in the Python environment where the code is being run.fixInstall the library using pip: `pip install opencensus-ext-azure`. -
HTTPSConnectionPool(...) Max retries exceeded with url: //v2.1/track (Caused by NewConnectionError(...): Failed to establish a new connection: [Errno 11001] getaddrinfo failed)
cause The exporter cannot establish a network connection to the Azure Monitor ingestion endpoint, often due to network issues, DNS resolution failures, firewall restrictions, or an incorrect connection string pointing to an unreachable host.fixEnsure network connectivity to Azure Monitor endpoints (`*.applicationinsights.azure.com`), verify DNS settings, check local and network firewall rules, and confirm that the `APPLICATIONINSIGHTS_CONNECTION_STRING` environment variable or the `connection_string` parameter in the exporter is correctly set with a valid Azure Monitor resource key. -
Logs not appearing in Application Insights / opencensus-ext-azure duplicated logs
cause Telemetry might not be sent due to incorrect logging level configuration, the `AzureLogHandler` being added multiple times to the root logger (especially in persistent environments like Databricks notebooks), or an invalid instrumentation key/connection string.fixVerify the logger's level is set appropriately (e.g., `logger.setLevel(logging.INFO)`), ensure the `AzureLogHandler` is instantiated and added only once to the logger, and double-check that the `connection_string` or `APPLICATIONINSIGHTS_CONNECTION_STRING` environment variable is correct and points to a valid Application Insights resource. -
ValueError: 'connection_string' is a required field
cause The `AzureLogHandler` or `AzureExporter` was initialized without providing the `connection_string` parameter, and the `APPLICATIONINSIGHTS_CONNECTION_STRING` environment variable, which is an alternative configuration method, was also not set.fixProvide the `connection_string` explicitly during the initialization of the exporter or handler, or set the `APPLICATIONINSIGHTS_CONNECTION_STRING` environment variable before running your application. Example: `AzureLogHandler(connection_string='InstrumentationKey=<your-instrumentation-key-here>')`. -
ModuleNotFoundError: No module named 'opencensus.ext.azure'
cause The 'opencensus-ext-azure' library has not been installed in the current Python environment.fixpip install opencensus-ext-azure
Warnings
- breaking The OpenCensus project, including `opencensus-ext-azure`, has officially transitioned to OpenTelemetry. While existing OpenCensus applications will continue to function, the project is in maintenance mode, meaning no new features will be added, and future development efforts are focused on OpenTelemetry. New applications should consider starting with OpenTelemetry.
- deprecated Active feature development for `opencensus-ext-azure` has ceased. The library will only receive critical bug fixes. This impacts long-term support and access to new Azure Monitor features.
- gotcha It is recommended to use the `APPLICATIONINSIGHTS_CONNECTION_STRING` environment variable instead of `APPINSIGHTS_INSTRUMENTATIONKEY` for configuration. Connection strings offer more flexibility and security, supporting endpoint customization and other settings.
- gotcha When integrating logging, ensure you don't add duplicate `AzureMonitorLogHandler` instances to the same logger or its ancestors, as this can lead to logs being sent multiple times.
- gotcha Compatibility issues can arise if the `opencensus` core library version does not meet the requirements specified by `opencensus-ext-azure`. Always ensure `opencensus` is installed within the required range.
Install
-
pip install opencensus-ext-azure -
pip install opencensus-ext-azure[azure_functions]
Imports
- AzureMonitorTraceExporter
from opencensus.ext.azure.trace_exporter import AzureMonitorTraceExporter
- AzureMonitorLogHandler
from opencensus.ext.azure.log_exporter import AzureMonitorLogHandler
- AzureMonitorMetricsExporter
from opencensus.ext.azure.metrics_exporter import AzureMonitorMetricsExporter
- Tracer
from opencensus.trace.tracer import Tracer
Quickstart
import os
import logging
from opencensus.ext.azure.log_exporter import AzureMonitorLogHandler
from opencensus.ext.azure.trace_exporter import AzureMonitorTraceExporter
from opencensus.trace.tracer import Tracer
from opencensus.trace.samplers import ProbabilitySampler
# Set your Azure Application Insights Connection String as an environment variable
# APPLICATIONINSIGHTS_CONNECTION_STRING='InstrumentationKey=YOUR_INSTRUMENTATION_KEY;IngestionEndpoint=https://eastus-8.in.applicationinsights.azure.com/'
CONNECTION_STRING = os.environ.get('APPLICATIONINSIGHTS_CONNECTION_STRING', '')
if not CONNECTION_STRING:
print("WARNING: APPLICATIONINSIGHTS_CONNECTION_STRING environment variable not set. Telemetry will not be sent.")
# --- Tracing Example ---
print("\n--- Tracing Example ---")
# Initialize a trace exporter
trace_exporter = AzureMonitorTraceExporter(
connection_string=CONNECTION_STRING
)
tracer = Tracer(exporter=trace_exporter, sampler=ProbabilitySampler(1.0))
with tracer.span(name='my_span'):
print(" Inside a traced span.")
with tracer.span(name='child_span'):
print(" Inside a child span.")
print(" Trace exported. Check Azure Portal after a short delay.")
# --- Logging Example ---
print("\n--- Logging Example ---")
# Initialize a log handler
handler = AzureMonitorLogHandler(
connection_string=CONNECTION_STRING
)
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
logger.addHandler(handler)
logger.info('This is an info log via Azure Monitor.')
logger.warning('This is a warning log.')
try:
1 / 0
except ZeroDivisionError:
logger.exception('An error occurred during division.')
print(" Logs exported. Check Azure Portal after a short delay.")
# In a real application, ensure exporters are properly shut down on exit
# trace_exporter.shutdown()
# handler.close()