1717from fastapi import FastAPI , Request
1818from fastapi .middleware .cors import CORSMiddleware
1919
20+ from opentelemetry .instrumentation .fastapi import FastAPIInstrumentor
21+
2022# Local imports
2123from middleware .health_check import HealthCheckMiddleware
2224from v4 .api .router import app_v4
@@ -51,20 +53,6 @@ async def lifespan(app: FastAPI):
5153 logger .info ("👋 MACAE application shutdown complete" )
5254
5355
54- # Check if the Application Insights Instrumentation Key is set in the environment variables
55- connection_string = config .APPLICATIONINSIGHTS_CONNECTION_STRING
56- if connection_string :
57- # Configure Application Insights if the Instrumentation Key is found
58- configure_azure_monitor (connection_string = connection_string )
59- logging .info (
60- "Application Insights configured with the provided Instrumentation Key"
61- )
62- else :
63- # Log a warning if the Instrumentation Key is not found
64- logging .warning (
65- "No Application Insights Instrumentation Key found. Skipping configuration"
66- )
67-
6856# Configure logging levels from environment variables
6957# logging.basicConfig(level=getattr(logging, config.AZURE_BASIC_LOGGING_LEVEL.upper(), logging.INFO))
7058
@@ -80,10 +68,32 @@ async def lifespan(app: FastAPI):
8068
8169logging .getLogger ("azure.core.pipeline.policies.http_logging_policy" ).setLevel (logging .WARNING )
8270
71+ # Suppress noisy Azure Monitor exporter "Transmission succeeded" logs
72+ logging .getLogger ("azure.monitor.opentelemetry.exporter.export._base" ).setLevel (logging .WARNING )
73+
8374# Initialize the FastAPI app
8475app = FastAPI (lifespan = lifespan )
8576
8677frontend_url = config .FRONTEND_SITE_NAME
78+ # Configure Azure Monitor and instrument FastAPI for OpenTelemetry
79+ # This enables automatic request tracing, dependency tracking, and proper operation_id
80+ if config .APPLICATIONINSIGHTS_CONNECTION_STRING :
81+ # Configure Application Insights telemetry with live metrics
82+ configure_azure_monitor (
83+ connection_string = config .APPLICATIONINSIGHTS_CONNECTION_STRING ,
84+ enable_live_metrics = True
85+ )
86+
87+ # Instrument FastAPI app — exclude WebSocket URLs to reduce telemetry noise
88+ FastAPIInstrumentor .instrument_app (
89+ app ,
90+ excluded_urls = "socket,ws"
91+ )
92+ logging .info ("Application Insights configured with live metrics and WebSocket filtering" )
93+ else :
94+ logging .warning (
95+ "No Application Insights connection string found. Telemetry disabled."
96+ )
8797
8898# Add this near the top of your app.py, after initializing the app
8999app .add_middleware (
0 commit comments