Request logging to Application insight does not get through when using http.status_code as key value

member45232 51 Reputation points
2022-07-25T17:37:22.33+00:00

This was very frustrating and time consuming to find out :-|

I have a python/fastapi app on Azure function that I tried for days to connect with Application insights with the recommended opencensus package and the code adapted from the documentation: https://learn.microsoft.com/en-us/azure/azure-monitor/app/opencensus-python-request#tracking-fastapi-applications

After hours of experimenting. I now get a "request"-type transaction in Application Insight with the correct values for http status and request url but only if I do NOT use the recommended key name http.status_code / http.url.

Instead I'm using "HTTP_STATUS_CODE" and "HTTP_URL" now which show up as "Custom Properties" in the end-to-end transaction. While the overview list says:

7/25/2022, 7:22:09 PM
Request URL: <empty>Response code: 0 Response time: <empty>

But if I use the "official" keynames my requests don't make it into application insights at all.... why?

Here is my so fast "best working" code:

class ApplicationInsightsMiddleware:  
  
    def __init__(self, app) -> None:  
        self.app = app  
  
    async def __call__(self, scope, receive, send):  
  
        exporter = AzureExporter(connection_string=app_insights_conn_string)  
        sampler = ProbabilitySampler(1.0)  
        tracer = Tracer(exporter=exporter, sampler=sampler)  
  
        async def send_wrapper(message):  
            if message["type"] == "http.response.start":  
                with tracer.span("request") as span:  
                    span.span_kind = SpanKind.SERVER  
                    tracer.add_attribute_to_current_span(  
                        attribute_key="HTTP_STATUS_CODE", attribute_value=str(message["status"])  
                    )  
                    tracer.add_attribute_to_current_span(  
                        attribute_key="HTTP_URL", attribute_value=scope["path"]  
                    )  
            await send(message)  
  
        await self.app(scope, receive, send_wrapper)  
  
  
fastapi_app.add_middleware(ApplicationInsightsMiddleware)  
Azure Monitor
Azure Monitor
An Azure service that is used to collect, analyze, and act on telemetry data from Azure and on-premises environments.
2,922 questions
{count} votes