opencensus-ext-azure 1.1.15
pip install opencensus-ext-azure
Released:
OpenCensus Azure Monitor Exporter
Navigation
Verified details
These details have been verified by PyPIMaintainers
π Avatar for jeremydvoss from gravatar.comjeremydvoss π Avatar for LeightonC from gravatar.com
LeightonC
Unverified details
These details have not been verified by PyPIProject links
Meta
- License: Apache Software License (Apache-2.0)
- Author: OpenCensus Authors
Classifiers
- Development Status
- Intended Audience
- License
- Programming Language
Project description
OpenCensus Azure Monitor exporters are on the path to deprecation. They will be officially unsupported by September 2024. Please migrate to the Azure Monitor OpenTelemetry Distro for the recommended βone-stop-shopβ solution or the Azure Monitor OpenTelemetry exporters for the more hand-on, configurable solution based on OpenTelemetry. Check out the migration guide on how to easily migrate Python code.
Installation
pip install opencensus-ext-azure
Prerequisites
Create an Azure Monitor resource and get the instrumentation key, more information can be found in the official docs.
Place your instrumentation key in a connection string and directly into your code.
Alternatively, you can specify your connection string in an environment variable APPLICATIONINSIGHTS_CONNECTION_STRING.
Usage
Log
The Azure Monitor Log Handler allows you to export Python logs to Azure Monitor.
This example shows how to send a warning level log to Azure Monitor.
importloggingfromopencensus.ext.azure.log_exporterimport AzureLogHandlerlogger = logging.getLogger(__name__)logger.addHandler(AzureLogHandler(connection_string='InstrumentationKey=<your-instrumentation_key-here>'))logger.warning('Hello, World!')
Correlation
You can enrich the logs with trace IDs and span IDs by using the logging integration.
Install the logging integration package using pip install opencensus-ext-logging.
importloggingfromopencensus.ext.azure.log_exporterimport AzureLogHandlerfromopencensus.ext.azure.trace_exporterimport AzureExporterfromopencensus.traceimport config_integrationfromopencensus.trace.samplersimport ProbabilitySamplerfromopencensus.trace.tracerimport Tracerconfig_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')with tracer.span(name='test'): logger.warning('In the span')logger.warning('After the span')
Custom Properties
You can also add custom properties to your log messages in the extra keyword 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_exporterimport AzureLogHandlerlogger = 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 Logs
You can pass a callback function to the exporter to process telemetry before it is exported.
Your callback function can return False if you do not want this envelope exported.
Your callback function must accept an envelope data type as its parameter.
You can see the schema for Azure Monitor data types in the envelopes here.
The AzureLogHandler handles ExceptionData and MessageData data types.
importloggingfromopencensus.ext.azure.log_exporterimport AzureLogHandlerlogger = logging.getLogger(__name__)# Callback function to append '_hello' to each log message telemetrydefcallback_function(envelope): envelope.data.baseData.message += '_hello' return Truehandler = AzureLogHandler(connection_string='InstrumentationKey=<your-instrumentation_key-here>')handler.add_telemetry_processor(callback_function)logger.addHandler(handler)logger.warning('Hello, World!')
Events
You can send customEvent telemetry in exactly the same way you would send trace telemetry except using the AzureEventHandler instead.
importloggingfromopencensus.ext.azure.log_exporterimport AzureEventHandlerlogger = logging.getLogger(__name__)logger.addHandler(AzureEventHandler(connection_string='InstrumentationKey=<your-instrumentation_key-here>'))logger.setLevel(logging.INFO)logger.info('Hello, World!')
Metrics
The Azure Monitor Metrics Exporter allows you to export metrics to Azure Monitor.
fromopencensus.ext.azureimport metrics_exporterfromopencensus.statsimport aggregation as aggregation_modulefromopencensus.statsimport measure as measure_modulefromopencensus.statsimport stats as stats_modulefromopencensus.statsimport view as view_modulefromopencensus.tagsimport tag_map as tag_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 metrics exporter = 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 counters
The exporter also includes a set of performance counters that are exported to Azure Monitor by default.
importpsutilimporttimefromopencensus.ext.azureimport metrics_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, ) for i in range(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 Metrics
You can pass a callback function to the exporter to process telemetry before it is exported.
Your callback function can return False if you do not want this envelope exported.
Your callback function must accept an envelope data type as its parameter.
You can see the schema for Azure Monitor data types in the envelopes here.
The MetricsExporter handles MetricData data types.
fromopencensus.ext.azureimport metrics_exporterfromopencensus.statsimport aggregation as aggregation_modulefromopencensus.statsimport measure as measure_modulefromopencensus.statsimport stats as stats_modulefromopencensus.statsimport view as view_modulefromopencensus.tagsimport tag_map as tag_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): return envelope.data.baseData.metrics[0].value > 0defmain(): # Enable metrics # Set the interval in seconds to 60s, which is the time interval application insights # aggregates your metrics exporter = 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()
Trace
The Azure Monitor Trace Exporter allows you to export OpenCensus traces to Azure Monitor.
This example shows how to send a span βhelloβ to Azure Monitor.
fromopencensus.ext.azure.trace_exporterimport AzureExporterfromopencensus.trace.samplersimport ProbabilitySamplerfromopencensus.trace.tracerimport Tracertracer = Tracer( exporter=AzureExporter( connection_string='InstrumentationKey=<your-instrumentation-key-here>' ), sampler=ProbabilitySampler(1.0))with tracer.span(name='hello'): print('Hello, World!')
Integrations
OpenCensus also supports several integrations which allows OpenCensus to integrate with third party libraries.
This example shows how to integrate with the requests library.
Install the requests integration package using pip install opencensus-ext-requests.
importrequestsfromopencensus.ext.azure.trace_exporterimport AzureExporterfromopencensus.traceimport config_integrationfromopencensus.trace.samplersimport ProbabilitySamplerfromopencensus.trace.tracerimport Tracerconfig_integration.trace_integrations(['requests'])tracer = Tracer( exporter=AzureExporter( connection_string='InstrumentationKey=<your-instrumentation-key-here>', ), sampler=ProbabilitySampler(1.0),)with tracer.span(name='parent'): response = requests.get(url='https://www.wikipedia.org/wiki/Rabbit')
Modifying Traces
You can pass a callback function to the exporter to process telemetry before it is exported.
Your callback function can return False if you do not want this envelope exported.
Your callback function must accept an envelope data type as its parameter.
You can see the schema for Azure Monitor data types in the envelopes here.
The AzureExporter handles Data data types.
importrequestsfromopencensus.ext.azure.trace_exporterimport AzureExporterfromopencensus.traceimport config_integrationfromopencensus.trace.samplersimport ProbabilitySamplerfromopencensus.trace.tracerimport Tracerconfig_integration.trace_integrations(['requests'])# Callback function to add os_type: linux to span propertiesdefcallback_function(envelope): envelope.data.baseData.properties['os_type'] = 'linux' return Trueexporter = AzureExporter( connection_string='InstrumentationKey=<your-instrumentation-key-here>')exporter.add_telemetry_processor(callback_function)tracer = Tracer(exporter=exporter, sampler=ProbabilitySampler(1.0))with tracer.span(name='parent'): response = requests.get(url='https://www.wikipedia.org/wiki/Rabbit')
Integrate with Azure Functions
Users who want to capture custom telemetry in Azure Functions environments are encouraged to used the OpenCensus Python Azure Functions extension. More details can be found in this document.
References
Project details
Verified details
These details have been verified by PyPIMaintainers
π Avatar for jeremydvoss from gravatar.comjeremydvoss π Avatar for LeightonC from gravatar.com
LeightonC
Unverified details
These details have not been verified by PyPIProject links
Meta
- License: Apache Software License (Apache-2.0)
- Author: OpenCensus Authors
Classifiers
- Development Status
- Intended Audience
- License
- Programming Language
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
Source Distribution
Built Distribution
Filter files by name, interpreter, ABI, and platform.
If you're not sure about the file name format, learn more about wheel file names.
Copy a direct link to the current filters
File details
Details for the file opencensus_ext_azure-1.1.15.tar.gz.
File metadata
- Download URL: opencensus_ext_azure-1.1.15.tar.gz
- Upload date:
- Size: 51.0 kB
- Tags: Source
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.12.10
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
8d108af15875ea3c52238646fba924c3ba9fbfaaf1fd0d350707dc5b7880ade7
|
|
| MD5 |
2da285ccd801e559909247ad233cf3c7
|
|
| BLAKE2b-256 |
54bf719a4a3885e6da101c47944e902ecd09287db237e766585951152b506a11
|
File details
Details for the file opencensus_ext_azure-1.1.15-py2.py3-none-any.whl.
File metadata
- Download URL: opencensus_ext_azure-1.1.15-py2.py3-none-any.whl
- Upload date:
- Size: 43.2 kB
- Tags: Python 2, Python 3
- Uploaded using Trusted Publishing? No
- Uploaded via: twine/6.1.0 CPython/3.12.10
File hashes
| Algorithm | Hash digest | |
|---|---|---|
| SHA256 |
6cf6102987ed2b9b64a7757291a0a67b09bf7a6869c3e9e2dac32888cafc06f6
|
|
| MD5 |
df12fa3162f889af861ac57b8e56ea7e
|
|
| BLAKE2b-256 |
ae7abd1dffd6a1ad07c1fd652054a33b7024745e989404c3681296d247a08895
|
