Package: opencensus-ext-azure
OpenCensus Azure Monitor exporters are on the path to deprecation. They will be officially unsupported by September 2024. Please migrate to theAzure Monitor OpenTelemetry Distrofor the recommended “one-stop-shop” solution or theAzure Monitor OpenTelemetry exportersfor the more hand-on, configurable solution based onOpenTelemetry.
Check out themigration guideon how to easily migrate Python code.Installationpip install opencensus-ext-azurePrerequisitesCreate an Azure Monitor resource and get the instrumentation key, more information can be found in the officialdocs.Place your instrumentation key in aconnection stringand directly into your code.Alternatively, you can specify yourconnection stringin an environment variableAPPLICATIONINSIGHTS_CONNECTION_STRING.UsageLogTheAzure Monitor Log Handlerallows you to export Python logs toAzure Monitor.This example shows how to send a warning level log to Azure Monitor.importloggingfromopencensus.ext.azure.log_exporterimportAzureLogHandlerlogger=logging.getLogger(__name__)logger.addHandler(AzureLogHandler(connection_string='InstrumentationKey=<your-instrumentation_key-here>'))logger.warning('Hello, World!')CorrelationYou can enrich the logs with trace IDs and span IDs by using thelogging integration.Install thelogging integration packageusingpip installopencensus-ext-logging.importloggingfromopencensus.ext.azure.log_exporterimportAzureLogHandlerfromopencensus.ext.azure.trace_exporterimportAzureExporterfromopencensus.traceimportconfig_integrationfromopencensus.trace.samplersimportProbabilitySamplerfromopencensus.trace.tracerimportTracerconfig_integration.trace_integrations(['logging'])logger=logging.getLogger(__name__)handler=AzureLogHandler(connection_string='InstrumentationKey=<your-instrumentation_key-here>')handler.setFormatter(logging.Formatter('%(traceId)s%(spanId)s%(message)s'))logger.addHandler(handler)tracer=Tracer(exporter=AzureExporter(connection_string='InstrumentationKey=<your-instrumentation_key-here>'),sampler=ProbabilitySampler(1.0))logger.warning('Before the span')withtracer.span(name='test'):logger.warning('In the span')logger.warning('After the span')Custom PropertiesYou can also add custom properties to your log messages in theextrakeyword argument using the custom_dimensions field.WARNING: For this feature to work, you need to pass a dictionary to the custom_dimensions field. If you pass arguments of any other type, the logger will ignore them.importloggingfromopencensus.ext.azure.log_exporterimportAzureLogHandlerlogger=logging.getLogger(__name__)logger.addHandler(AzureLogHandler(connection_string='InstrumentationKey=<your-instrumentation_key-here>'))properties={'custom_dimensions':{'key_1':'value_1','key_2':'value_2'}}logger.warning('action',extra=properties)Modifying LogsYou can pass a callback function to the exporter to process telemetry before it is exported.Your callback function can returnFalseif you do not want this envelope exported.Your callback function must accept anenvelopedata type as its parameter.You can see the schema for Azure Monitor data types in the envelopeshere.TheAzureLogHandlerhandlesExceptionDataandMessageDatadata types.importloggingfromopencensus.ext.azure.log_exporterimportAzureLogHandlerlogger=logging.getLogger(__name__)# Callback function to append '_hello' to each log message telemetrydefcallback_function(envelope):envelope.data.baseData.message+='_hello'returnTruehandler=AzureLogHandler(connection_string='InstrumentationKey=<your-instrumentation_key-here>')handler.add_telemetry_processor(callback_function)logger.addHandler(handler)logger.warning('Hello, World!')EventsYou can sendcustomEventtelemetry in exactly the same way you would sendtracetelemetry except using theAzureEventHandlerinstead.importloggingfromopencensus.ext.azure.log_exporterimportAzureEventHandlerlogger=logging.getLogger(__name__)logger.addHandler(AzureEventHandler(connection_string='InstrumentationKey=<your-instrumentation_key-here>'))logger.setLevel(logging.INFO)logger.info('Hello, World!')MetricsTheAzure Monitor Metrics Exporterallows you to export metrics toAzure Monitor.fromopencensus.ext.azureimportmetrics_exporterfromopencensus.statsimportaggregationasaggregation_modulefromopencensus.statsimportmeasureasmeasure_modulefromopencensus.statsimportstatsasstats_modulefromopencensus.statsimportviewasview_modulefromopencensus.tagsimporttag_mapastag_map_modulestats=stats_module.statsview_manager=stats.view_managerstats_recorder=stats.stats_recorderCARROTS_MEASURE=measure_module.MeasureInt("carrots","number of carrots","carrots")CARROTS_VIEW=view_module.View("carrots_view","number of carrots",[],CARROTS_MEASURE,aggregation_module.CountAggregation())defmain():# Enable metrics# Set the interval in seconds to 60s, which is the time interval application insights# aggregates your metricsexporter=metrics_exporter.new_metrics_exporter(connection_string='InstrumentationKey=<your-instrumentation-key-here>')view_manager.register_exporter(exporter)view_manager.register_view(CARROTS_VIEW)mmap=stats_recorder.new_measurement_map()tmap=tag_map_module.TagMap()mmap.measure_int_put(CARROTS_MEASURE,1000)mmap.record(tmap)print("Done recording metrics")if__name__=="__main__":main()Performance countersThe exporter also includes a set of performance counters that are exported to Azure Monitor by default.importpsutilimporttimefromopencensus.ext.azureimportmetrics_exporterdefmain():# Performance counters are sent by default. You can disable performance counters by# passing in enable_standard_metrics=False into the constructor of# new_metrics_exporter()_exporter=metrics_exporter.new_metrics_exporter(connection_string='InstrumentationKey=<your-instrumentation-key-here>',export_interval=60,)foriinrange(100):print(psutil.virtual_memory())time.sleep(5)print("Done recording metrics")if__name__=="__main__":main()Below is a list of performance counters that are currently available:Available Memory (bytes)CPU Processor Time (percentage)Incoming Request Rate (per second)Incoming Request Average Execution Time (milliseconds)Process CPU Usage (percentage)Process Private Bytes (bytes)Modifying MetricsYou can pass a callback function to the exporter to process telemetry before it is exported.Your callback function can returnFalseif you do not want this envelope exported.Your callback function must accept anenvelopedata type as its parameter.You can see the schema for Azure Monitor data types in the envelopeshere.TheMetricsExporterhandlesMetricDatadata types.fromopencensus.ext.azureimportmetrics_exporterfromopencensus.statsimportaggregationasaggregation_modulefromopencensus.statsimportmeasureasmeasure_modulefromopencensus.statsimportstatsasstats_modulefromopencensus.statsimportviewasview_modulefromopencensus.tagsimporttag_mapastag_map_modulestats=stats_module.statsview_manager=stats.view_managerstats_recorder=stats.stats_recorderCARROTS_MEASURE=measure_module.MeasureInt("carrots","number of carrots","carrots")CARROTS_VIEW=view_module.View("carrots_view","number of carrots",[],CARROTS_MEASURE,aggregation_module.CountAggregation())# Callback function to only export the metric if value is greater than 0defcallback_function(envelope):returnenvelope.data.baseData.metrics[0].value>0defmain():# Enable metrics# Set the interval in seconds to 60s, which is the time interval application insights# aggregates your metricsexporter=metrics_exporter.new_metrics_exporter(connection_string='InstrumentationKey=<your-instrumentation-key-here>',export_interval=60,)exporter.add_telemetry_processor(callback_function)view_manager.register_exporter(exporter)view_manager.register_view(CARROTS_VIEW)mmap=stats_recorder.new_measurement_map()tmap=tag_map_module.TagMap()mmap.measure_int_put(CARROTS_MEASURE,1000)mmap.record(tmap)print("Done recording metrics")if__name__=="__main__":main()TraceTheAzure Monitor Trace Exporterallows you to exportOpenCensustraces toAzure Monitor.This example shows how to send a span “hello” to Azure Monitor.fromopencensus.ext.azure.trace_exporterimportAzureExporterfromopencensus.trace.samplersimportProbabilitySamplerfromopencensus.trace.tracerimportTracertracer=Tracer(exporter=AzureExporter(connection_string='InstrumentationKey=<your-instrumentation-key-here>'),sampler=ProbabilitySampler(1.0))withtracer.span(name='hello'):print('Hello, World!')IntegrationsOpenCensus also supports severalintegrationswhich allows OpenCensus to integrate with third party libraries.This example shows how to integrate with therequestslibrary.Install therequests integration packageusingpip installopencensus-ext-requests.importrequestsfromopencensus.ext.azure.trace_exporterimportAzureExporterfromopencensus.traceimportconfig_integrationfromopencensus.trace.samplersimportProbabilitySamplerfromopencensus.trace.tracerimportTracerconfig_integration.trace_integrations(['requests'])tracer=Tracer(exporter=AzureExporter(connection_string='InstrumentationKey=<your-instrumentation-key-here>',),sampler=ProbabilitySampler(1.0),)withtracer.span(name='parent'):response=requests.get(url='https://www.wikipedia.org/wiki/Rabbit')Modifying TracesYou can pass a callback function to the exporter to process telemetry before it is exported.Your callback function can returnFalseif you do not want this envelope exported.Your callback function must accept anenvelopedata type as its parameter.You can see the schema for Azure Monitor data types in the envelopeshere.TheAzureExporterhandlesDatadata types.importrequestsfromopencensus.ext.azure.trace_exporterimportAzureExporterfromopencensus.traceimportconfig_integrationfromopencensus.trace.samplersimportProbabilitySamplerfromopencensus.trace.tracerimportTracerconfig_integration.trace_integrations(['requests'])# Callback function to add os_type: linux to span propertiesdefcallback_function(envelope):envelope.data.baseData.properties['os_type']='linux'returnTrueexporter=AzureExporter(connection_string='InstrumentationKey=<your-instrumentation-key-here>')exporter.add_telemetry_processor(callback_function)tracer=Tracer(exporter=exporter,sampler=ProbabilitySampler(1.0))withtracer.span(name='parent'):response=requests.get(url='https://www.wikipedia.org/wiki/Rabbit')Integrate with Azure FunctionsUsers who want to capture custom telemetry in Azure Functions environments are encouraged to used the OpenCensus Python Azure Functionsextension. More details can be found in thisdocument.ReferencesAzure MonitorOfficial Microsoft DocsExamplesOpenCensus Project