Skip to content

Commit f717dc0

Browse files
author
ks6088ts
committed
add flaky API to raise an exception
1 parent 79f6942 commit f717dc0

File tree

1 file changed

+26
-2
lines changed

1 file changed

+26
-2
lines changed

template_fastapi/app.py

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,18 +4,30 @@
44
"""
55

66
import random
7+
import uuid
78
from os import getenv
89

910
from azure.monitor.opentelemetry import configure_azure_monitor
1011
from fastapi import FastAPI, HTTPException, Query
1112
from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor
13+
from opentelemetry.trace import Span
1214
from pydantic import BaseModel
1315

1416
app = FastAPI()
1517

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")
1820
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+
1931
configure_azure_monitor(
2032
connection_string=AZURE_CONNECTION_STRING,
2133
)
@@ -162,3 +174,15 @@ async def flaky(failure_rate: int):
162174
return {
163175
"message": "Request succeeded",
164176
}
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

Comments
 (0)