OpenCensus Azure Monitor Exporter

1.1.15 · maintenance · verified Thu Apr 09

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.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to set up and use the `AzureMonitorTraceExporter` for distributed tracing and `AzureMonitorLogHandler` for sending application logs to Azure Application Insights. Ensure the `APPLICATIONINSIGHTS_CONNECTION_STRING` environment variable is set for telemetry to be sent successfully.

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

view raw JSON →