prompt: We are currently solving the following issue within our repository. Here is the issue text:
  --- BEGIN ISSUE ---
  API app not reporting requests to AppInsights
  **Description**
  Ensure opencensus reports http requests to app insights.
  
  --- END ISSUE ---
  
  Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
  --- BEGIN FILES ---
  Path: `api_app/main.py`
  Content:
  ```
  1 import logging
  2 import uvicorn
  3 
  4 from fastapi import FastAPI
  5 from fastapi.exceptions import RequestValidationError
  6 from fastapi_utils.tasks import repeat_every
  7 from starlette.exceptions import HTTPException
  8 from starlette.middleware.errors import ServerErrorMiddleware
  9 
  10 from api.routes.api import router as api_router
  11 from api.routes.api import tags_metadata
  12 from api.errors.http_error import http_error_handler
  13 from api.errors.validation_error import http422_error_handler
  14 from api.errors.generic_error import generic_error_handler
  15 from core import config
  16 from core.events import create_start_app_handler, create_stop_app_handler
  17 from services.logging import disable_unwanted_loggers, initialize_logging
  18 from service_bus.deployment_status_update import receive_message_and_update_deployment
  19 
  20 
  21 def get_application() -> FastAPI:
  22     application = FastAPI(
  23         title=config.PROJECT_NAME,
  24         debug=config.DEBUG,
  25         description=config.API_DESCRIPTION,
  26         version=config.VERSION,
  27         docs_url="/api/docs",
  28         swagger_ui_oauth2_redirect_url="/api/docs/oauth2-redirect",
  29         swagger_ui_init_oauth={
  30             "usePkceWithAuthorizationCodeGrant": True,
  31             "clientId": config.SWAGGER_UI_CLIENT_ID,
  32             "scopes": ["openid", "offline_access", f"api://{config.API_CLIENT_ID}/Workspace.Read", f"api://{config.API_CLIENT_ID}/Workspace.Write"]
  33         },
  34         openapi_tags=tags_metadata
  35     )
  36 
  37     application.add_event_handler("startup", create_start_app_handler(application))
  38     application.add_event_handler("shutdown", create_stop_app_handler(application))
  39 
  40     application.add_middleware(ServerErrorMiddleware, handler=generic_error_handler)
  41     application.add_exception_handler(HTTPException, http_error_handler)
  42     application.add_exception_handler(RequestValidationError, http422_error_handler)
  43 
  44     application.include_router(api_router, prefix=config.API_PREFIX)
  45     return application
  46 
  47 
  48 app = get_application()
  49 
  50 
  51 @app.on_event("startup")
  52 async def initialize_logging_on_startup():
  53     if config.DEBUG:
  54         initialize_logging(logging.DEBUG)
  55     else:
  56         initialize_logging(logging.INFO)
  57 
  58     disable_unwanted_loggers()
  59 
  60 
  61 @app.on_event("startup")
  62 @repeat_every(seconds=20, wait_first=True, logger=logging.getLogger())
  63 async def update_deployment_status() -> None:
  64     await receive_message_and_update_deployment(app)
  65 
  66 
  67 if __name__ == "__main__":
  68     uvicorn.run(app, host="0.0.0.0", port=8000)
  69
  ```
  
  Path: `api_app/_version.py`
  Content:
  ```
  1 __version__ = "0.1.1"
  2
  ```
  --- END FILES ---
  
  Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.
  
  Here is an example:
  
  ```diff
  diff --git a/examples/server_async.py b/examples/server_async.py
  --- a/examples/server_async.py
  +++ b/examples/server_async.py
  @@ -313,4 +313,4 @@
   
   
   if __name__ == "__main__":
  -    asyncio.run(run_async_server("."), debug=True)
  +    asyncio.run(run_async_server(), debug=True)
  diff --git a/examples/server_sync.py b/examples/server_sync.py
  --- a/examples/server_sync.py
  +++ b/examples/server_sync.py
  @@ -313,5 +313,5 @@
   
   
   if __name__ == "__main__":
  -    server = run_sync_server(".")
  +    server = run_sync_server()
       server.shutdown()
  
  ```
  
golden_diff: diff --git a/api_app/_version.py b/api_app/_version.py
  --- a/api_app/_version.py
  +++ b/api_app/_version.py
  @@ -1 +1 @@
  -__version__ = "0.1.1"
  +__version__ = "0.1.3"
  diff --git a/api_app/main.py b/api_app/main.py
  --- a/api_app/main.py
  +++ b/api_app/main.py
  @@ -1,7 +1,8 @@
   import logging
  +import os
   import uvicorn
   
  -from fastapi import FastAPI
  +from fastapi import FastAPI, Request
   from fastapi.exceptions import RequestValidationError
   from fastapi_utils.tasks import repeat_every
   from starlette.exceptions import HTTPException
  @@ -17,6 +18,16 @@
   from services.logging import disable_unwanted_loggers, initialize_logging
   from service_bus.deployment_status_update import receive_message_and_update_deployment
   
  +# Opencensus Azure imports
  +from opencensus.ext.azure.trace_exporter import AzureExporter
  +from opencensus.trace.attributes_helper import COMMON_ATTRIBUTES
  +from opencensus.trace.samplers import ProbabilitySampler
  +from opencensus.trace.span import SpanKind
  +from opencensus.trace.tracer import Tracer
  +
  +HTTP_URL = COMMON_ATTRIBUTES['HTTP_URL']
  +HTTP_STATUS_CODE = COMMON_ATTRIBUTES['HTTP_STATUS_CODE']
  +
   
   def get_application() -> FastAPI:
       application = FastAPI(
  @@ -64,5 +75,19 @@
       await receive_message_and_update_deployment(app)
   
   
  +@app.middleware("http")
  +async def add_process_time_header(request: Request, call_next):
  +    tracer = Tracer(exporter=AzureExporter(connection_string=f'InstrumentationKey={os.getenv("APPINSIGHTS_INSTRUMENTATIONKEY")}'), sampler=ProbabilitySampler(1.0))
  +    with tracer.span("main") as span:
  +        span.span_kind = SpanKind.SERVER
  +
  +        response = await call_next(request)
  +
  +        tracer.add_attribute_to_current_span(attribute_key=HTTP_STATUS_CODE, attribute_value=response.status_code)
  +        tracer.add_attribute_to_current_span(attribute_key=HTTP_URL, attribute_value=str(request.url))
  +
  +    return response
  +
  +
   if __name__ == "__main__":
       uvicorn.run(app, host="0.0.0.0", port=8000)
  
verification_info: {"golden_diff": "diff --git a/api_app/_version.py b/api_app/_version.py\n--- a/api_app/_version.py\n+++ b/api_app/_version.py\n@@ -1 +1 @@\n-__version__ = \"0.1.1\"\n+__version__ = \"0.1.3\"\ndiff --git a/api_app/main.py b/api_app/main.py\n--- a/api_app/main.py\n+++ b/api_app/main.py\n@@ -1,7 +1,8 @@\n import logging\n+import os\n import uvicorn\n \n-from fastapi import FastAPI\n+from fastapi import FastAPI, Request\n from fastapi.exceptions import RequestValidationError\n from fastapi_utils.tasks import repeat_every\n from starlette.exceptions import HTTPException\n@@ -17,6 +18,16 @@\n from services.logging import disable_unwanted_loggers, initialize_logging\n from service_bus.deployment_status_update import receive_message_and_update_deployment\n \n+# Opencensus Azure imports\n+from opencensus.ext.azure.trace_exporter import AzureExporter\n+from opencensus.trace.attributes_helper import COMMON_ATTRIBUTES\n+from opencensus.trace.samplers import ProbabilitySampler\n+from opencensus.trace.span import SpanKind\n+from opencensus.trace.tracer import Tracer\n+\n+HTTP_URL = COMMON_ATTRIBUTES['HTTP_URL']\n+HTTP_STATUS_CODE = COMMON_ATTRIBUTES['HTTP_STATUS_CODE']\n+\n \n def get_application() -> FastAPI:\n     application = FastAPI(\n@@ -64,5 +75,19 @@\n     await receive_message_and_update_deployment(app)\n \n \n+@app.middleware(\"http\")\n+async def add_process_time_header(request: Request, call_next):\n+    tracer = Tracer(exporter=AzureExporter(connection_string=f'InstrumentationKey={os.getenv(\"APPINSIGHTS_INSTRUMENTATIONKEY\")}'), sampler=ProbabilitySampler(1.0))\n+    with tracer.span(\"main\") as span:\n+        span.span_kind = SpanKind.SERVER\n+\n+        response = await call_next(request)\n+\n+        tracer.add_attribute_to_current_span(attribute_key=HTTP_STATUS_CODE, attribute_value=response.status_code)\n+        tracer.add_attribute_to_current_span(attribute_key=HTTP_URL, attribute_value=str(request.url))\n+\n+    return response\n+\n+\n if __name__ == \"__main__\":\n     uvicorn.run(app, host=\"0.0.0.0\", port=8000)\n", "issue": "API app not reporting requests to AppInsights\n**Description**\r\nEnsure opencensus reports http requests to app insights.\n", "before_files": [{"content": "import logging\nimport uvicorn\n\nfrom fastapi import FastAPI\nfrom fastapi.exceptions import RequestValidationError\nfrom fastapi_utils.tasks import repeat_every\nfrom starlette.exceptions import HTTPException\nfrom starlette.middleware.errors import ServerErrorMiddleware\n\nfrom api.routes.api import router as api_router\nfrom api.routes.api import tags_metadata\nfrom api.errors.http_error import http_error_handler\nfrom api.errors.validation_error import http422_error_handler\nfrom api.errors.generic_error import generic_error_handler\nfrom core import config\nfrom core.events import create_start_app_handler, create_stop_app_handler\nfrom services.logging import disable_unwanted_loggers, initialize_logging\nfrom service_bus.deployment_status_update import receive_message_and_update_deployment\n\n\ndef get_application() -> FastAPI:\n    application = FastAPI(\n        title=config.PROJECT_NAME,\n        debug=config.DEBUG,\n        description=config.API_DESCRIPTION,\n        version=config.VERSION,\n        docs_url=\"/api/docs\",\n        swagger_ui_oauth2_redirect_url=\"/api/docs/oauth2-redirect\",\n        swagger_ui_init_oauth={\n            \"usePkceWithAuthorizationCodeGrant\": True,\n            \"clientId\": config.SWAGGER_UI_CLIENT_ID,\n            \"scopes\": [\"openid\", \"offline_access\", f\"api://{config.API_CLIENT_ID}/Workspace.Read\", f\"api://{config.API_CLIENT_ID}/Workspace.Write\"]\n        },\n        openapi_tags=tags_metadata\n    )\n\n    application.add_event_handler(\"startup\", create_start_app_handler(application))\n    application.add_event_handler(\"shutdown\", create_stop_app_handler(application))\n\n    application.add_middleware(ServerErrorMiddleware, handler=generic_error_handler)\n    application.add_exception_handler(HTTPException, http_error_handler)\n    application.add_exception_handler(RequestValidationError, http422_error_handler)\n\n    application.include_router(api_router, prefix=config.API_PREFIX)\n    return application\n\n\napp = get_application()\n\n\n@app.on_event(\"startup\")\nasync def initialize_logging_on_startup():\n    if config.DEBUG:\n        initialize_logging(logging.DEBUG)\n    else:\n        initialize_logging(logging.INFO)\n\n    disable_unwanted_loggers()\n\n\n@app.on_event(\"startup\")\n@repeat_every(seconds=20, wait_first=True, logger=logging.getLogger())\nasync def update_deployment_status() -> None:\n    await receive_message_and_update_deployment(app)\n\n\nif __name__ == \"__main__\":\n    uvicorn.run(app, host=\"0.0.0.0\", port=8000)\n", "path": "api_app/main.py"}, {"content": "__version__ = \"0.1.1\"\n", "path": "api_app/_version.py"}], "after_files": [{"content": "import logging\nimport os\nimport uvicorn\n\nfrom fastapi import FastAPI, Request\nfrom fastapi.exceptions import RequestValidationError\nfrom fastapi_utils.tasks import repeat_every\nfrom starlette.exceptions import HTTPException\nfrom starlette.middleware.errors import ServerErrorMiddleware\n\nfrom api.routes.api import router as api_router\nfrom api.routes.api import tags_metadata\nfrom api.errors.http_error import http_error_handler\nfrom api.errors.validation_error import http422_error_handler\nfrom api.errors.generic_error import generic_error_handler\nfrom core import config\nfrom core.events import create_start_app_handler, create_stop_app_handler\nfrom services.logging import disable_unwanted_loggers, initialize_logging\nfrom service_bus.deployment_status_update import receive_message_and_update_deployment\n\n# Opencensus Azure imports\nfrom opencensus.ext.azure.trace_exporter import AzureExporter\nfrom opencensus.trace.attributes_helper import COMMON_ATTRIBUTES\nfrom opencensus.trace.samplers import ProbabilitySampler\nfrom opencensus.trace.span import SpanKind\nfrom opencensus.trace.tracer import Tracer\n\nHTTP_URL = COMMON_ATTRIBUTES['HTTP_URL']\nHTTP_STATUS_CODE = COMMON_ATTRIBUTES['HTTP_STATUS_CODE']\n\n\ndef get_application() -> FastAPI:\n    application = FastAPI(\n        title=config.PROJECT_NAME,\n        debug=config.DEBUG,\n        description=config.API_DESCRIPTION,\n        version=config.VERSION,\n        docs_url=\"/api/docs\",\n        swagger_ui_oauth2_redirect_url=\"/api/docs/oauth2-redirect\",\n        swagger_ui_init_oauth={\n            \"usePkceWithAuthorizationCodeGrant\": True,\n            \"clientId\": config.SWAGGER_UI_CLIENT_ID,\n            \"scopes\": [\"openid\", \"offline_access\", f\"api://{config.API_CLIENT_ID}/Workspace.Read\", f\"api://{config.API_CLIENT_ID}/Workspace.Write\"]\n        },\n        openapi_tags=tags_metadata\n    )\n\n    application.add_event_handler(\"startup\", create_start_app_handler(application))\n    application.add_event_handler(\"shutdown\", create_stop_app_handler(application))\n\n    application.add_middleware(ServerErrorMiddleware, handler=generic_error_handler)\n    application.add_exception_handler(HTTPException, http_error_handler)\n    application.add_exception_handler(RequestValidationError, http422_error_handler)\n\n    application.include_router(api_router, prefix=config.API_PREFIX)\n    return application\n\n\napp = get_application()\n\n\n@app.on_event(\"startup\")\nasync def initialize_logging_on_startup():\n    if config.DEBUG:\n        initialize_logging(logging.DEBUG)\n    else:\n        initialize_logging(logging.INFO)\n\n    disable_unwanted_loggers()\n\n\n@app.on_event(\"startup\")\n@repeat_every(seconds=20, wait_first=True, logger=logging.getLogger())\nasync def update_deployment_status() -> None:\n    await receive_message_and_update_deployment(app)\n\n\n@app.middleware(\"http\")\nasync def add_process_time_header(request: Request, call_next):\n    tracer = Tracer(exporter=AzureExporter(connection_string=f'InstrumentationKey={os.getenv(\"APPINSIGHTS_INSTRUMENTATIONKEY\")}'), sampler=ProbabilitySampler(1.0))\n    with tracer.span(\"main\") as span:\n        span.span_kind = SpanKind.SERVER\n\n        response = await call_next(request)\n\n        tracer.add_attribute_to_current_span(attribute_key=HTTP_STATUS_CODE, attribute_value=response.status_code)\n        tracer.add_attribute_to_current_span(attribute_key=HTTP_URL, attribute_value=str(request.url))\n\n    return response\n\n\nif __name__ == \"__main__\":\n    uvicorn.run(app, host=\"0.0.0.0\", port=8000)\n", "path": "api_app/main.py"}, {"content": "__version__ = \"0.1.3\"\n", "path": "api_app/_version.py"}]}