|
9 | 9 |
|
10 | 10 | from azure.monitor.opentelemetry import configure_azure_monitor
|
11 | 11 | from fastapi import FastAPI, HTTPException, Query
|
| 12 | +from opentelemetry import trace |
12 | 13 | from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor
|
| 14 | +from opentelemetry.sdk.trace import TracerProvider |
| 15 | +from opentelemetry.sdk.trace.export import ( |
| 16 | + BatchSpanProcessor, |
| 17 | + ConsoleSpanExporter, |
| 18 | +) |
13 | 19 | from opentelemetry.trace import Span
|
14 | 20 | from pydantic import BaseModel
|
15 | 21 |
|
| 22 | +trace.set_tracer_provider(TracerProvider()) |
| 23 | +trace.get_tracer_provider().add_span_processor(BatchSpanProcessor(ConsoleSpanExporter())) |
| 24 | +tracer = trace.get_tracer(__name__) |
| 25 | + |
16 | 26 | app = FastAPI()
|
17 | 27 |
|
18 | 28 | # If APPLICATIONINSIGHTS_CONNECTION_STRING exists, configure Azure Monitor
|
@@ -187,3 +197,27 @@ async def flaky_exception():
|
187 | 197 | status_code=500,
|
188 | 198 | detail="Simulated exception",
|
189 | 199 | )
|
| 200 | + |
| 201 | + |
| 202 | +# Add a heavy synchronous endpoint which receives milliseconds to sleep |
| 203 | +@app.get("/heavy_sync/{sleep_ms}", tags=["heavy"], operation_id="heavy_sync_with_sleep") |
| 204 | +async def heavy_sync_with_sleep(sleep_ms: int): |
| 205 | + """ |
| 206 | + A heavy synchronous endpoint that sleeps for the specified number of milliseconds. |
| 207 | +
|
| 208 | + This simulates a long-running synchronous operation. |
| 209 | + """ |
| 210 | + if sleep_ms < 0: |
| 211 | + raise HTTPException( |
| 212 | + status_code=400, |
| 213 | + detail="Sleep time must be a non-negative integer", |
| 214 | + ) |
| 215 | + |
| 216 | + import time |
| 217 | + |
| 218 | + with tracer.start_as_current_span("foo"): |
| 219 | + print(f"Sleeping for {sleep_ms} milliseconds") |
| 220 | + time.sleep(sleep_ms / 1000.0) |
| 221 | + return { |
| 222 | + "message": f"Slept for {sleep_ms} milliseconds", |
| 223 | + } |
0 commit comments