Fix for Python Requests lineage with Azure Application Insights
OpenCensus provides a great mechanism for distributed tracing of requests through your microservice architecture. If you are using Requests to communicate with another service and you are using the Azure Application Insights as the OpenCensus backend, there is a bug where the requests API will create two spans and the dependency to the second service will be lost. To fix this, override the envelope.data.baseData.type
for all HTTP requests created by Requests. The example below shows how you would fix the issue, and after that is implemented you will see the dependency between the source and destination of a request correctly updated on Application Insights.
import requests
from opencensus.trace import config_integration
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:
config_integration.trace_integrations(['requests'])
app_insights_exporter=AzureExporter()
tracer = Tracer(exporter=app_insights_exporter, sampler=ProbabilitySampler(rate=1.0))
def callback_function(envelope):
# Override the type in the envelope if the properties are set to http
# This is a hack since the requests API integrate creates two spans
# which causes the Application Map to not link this to the dependent service.
if 'type' in envelope.data.baseData.properties and envelope.data.baseData.properties['type'] == 'HTTP':
envelope.data.baseData.type = 'HTTP'
return True
# add the call back
app_insights_exporter.add_telemetry_processor(callback_function)
You need to add the following PIP dependencies:
opencensus
opencensus-context==0.1.1
opencensus-ext-azure
opencensus-ext-requests