Auto Instrumenting Python FastAPI and Monitoring with Azure Application Insights — Easily!

Theo McCabe
2 min readJan 10, 2024

--

Coming from a C# background — I found monitoring my python FastAPI application with Azure Application Insights stupidly difficult. Mainly due to a lack of direct support in Azure or documentation for doing it manually.

In C#, you can automatically instrument on App Insights without adding a single line of code. There is no equivalent option for python.

However, you can achieve a decent first pass at auto instrumenting your python app using open telemetry, a few simple lines of code and some environment variables. Here’s how…

(I’ll skip the B******t now — just code.)

Also — here is a stock image of a dog with a croissant
opentelemetry-api >= 1.10.0
opentelemetry-sdk >= 1.10.0
azure-monitor-opentelemetry >= 1.1.1
from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor
from azure.monitor.opentelemetry import configure_azure_monitor
from opentelemetry import trace
from opentelemetry.trace import (
get_tracer_provider,
)
from opentelemetry.propagate import extract
from logging import getLogger, INFO

if os.getenv("APPLICATIONINSIGHTS_CONNECTION_STRING"):
configure_azure_monitor()

tracer = trace.get_tracer(__name__,
tracer_provider=get_tracer_provider())

logger = getLogger(__name__)

app = FastAPI()

FastAPIInstrumentor.instrument_app(app)

And that’s the code. It depends on 2 environment variables:

APPLICATIONINSIGHTS_CONNECTION_STRING="---your connection string---"
OTEL_EXPERIMENTAL_RESOURCE_DETECTORS="azure_app_service"

I couldn’t find a complete working solution on the internet, or on ChatGPT. So Hopefully this is helpful for you. Credit where its due — most of it came from this article which didn’t quite work for me but gave me most of the code.

Enjoy

--

--