|
4 | 4 | """
|
5 | 5 |
|
6 | 6 | import random
|
| 7 | +import uuid |
7 | 8 | from os import getenv
|
8 | 9 |
|
9 | 10 | from azure.monitor.opentelemetry import configure_azure_monitor
|
10 | 11 | from fastapi import FastAPI, HTTPException, Query
|
11 | 12 | from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor
|
| 13 | +from opentelemetry.trace import Span |
12 | 14 | from pydantic import BaseModel
|
13 | 15 |
|
14 | 16 | app = FastAPI()
|
15 | 17 |
|
16 |
| -# If AZURE_APPLICATIONINSIGHTS_CONNECTION_STRING exists, configure Azure Monitor |
17 |
| -AZURE_CONNECTION_STRING = getenv("AZURE_APPLICATIONINSIGHTS_CONNECTION_STRING") |
| 18 | +# If APPLICATIONINSIGHTS_CONNECTION_STRING exists, configure Azure Monitor |
| 19 | +AZURE_CONNECTION_STRING = getenv("APPLICATIONINSIGHTS_CONNECTION_STRING") |
18 | 20 | if AZURE_CONNECTION_STRING:
|
| 21 | + |
| 22 | + def server_request_hook(span: Span, scope: dict): |
| 23 | + if span and span.is_recording(): |
| 24 | + try: |
| 25 | + # Application Insights に送るデータにユーザ ID を追加する |
| 26 | + user_id = uuid.uuid4().hex # Replace with actual user ID retrieval logic |
| 27 | + span.set_attribute("enduser.id", user_id) |
| 28 | + except KeyError: |
| 29 | + pass |
| 30 | + |
19 | 31 | configure_azure_monitor(
|
20 | 32 | connection_string=AZURE_CONNECTION_STRING,
|
21 | 33 | )
|
@@ -162,3 +174,15 @@ async def flaky(failure_rate: int):
|
162 | 174 | return {
|
163 | 175 | "message": "Request succeeded",
|
164 | 176 | }
|
| 177 | + |
| 178 | + |
| 179 | +# Add flaky API which raises an exception |
| 180 | +@app.get("/flaky/exception", tags=["flaky"], operation_id="flaky_exception") |
| 181 | +async def flaky_exception(): |
| 182 | + """ |
| 183 | + A flaky endpoint that always raises an exception. |
| 184 | + """ |
| 185 | + raise HTTPException( |
| 186 | + status_code=500, |
| 187 | + detail="Simulated exception", |
| 188 | + ) |
0 commit comments