Set Azure Application Insights application name with Python API

Azure Application Insights is an awesome way to track metrics or logs in your Python application using the OpenCensus API. Application Insights has a Connection String that needs to be set in the APPLICATIONINSIGHTS_CONNECTION_STRING environment variable for the OpenCensus API to use with the AzureExporter. When you go to Application Insights, the name of your application, will be the filename of your Python script. If you would like to use a different name, override the ai.cloud.role attribute by overriding the add_telemtry_processor callback. The callback is invoked for each event that is sent to Application Insights.

from opencensus.ext.azure.trace_exporter import AzureExporter
from opencensus.trace.samplers import ProbabilitySampler
from opencensus.trace.tracer import Tracer

# register exporter for Azure Application Insights
if "APPLICATIONINSIGHTS_CONNECTION_STRING" in os.environ:
    app_insights_exporter=AzureExporter()
    tracer = Tracer(exporter=app_insights_exporter, sampler=ProbabilitySampler(rate=1.0))

    # Callback function to override the name of the application
    # without this, the API will report the name of the file as the application
    def callback_function(envelope):
        envelope.tags['ai.cloud.role'] = "custom_app_name"
        return True

    # add the call back
    app_insights_exporter.add_telemetry_processor(callback_function)

Required PIP depenedencies:

opencensus
opencensus-context==0.1.1
opencensus-ext-azure
opencensus-ext-flask
Previous
Previous

Fix for Python Requests lineage with Azure Application Insights

Next
Next

How to manage multiple subscription Ids with az command