|
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 |
13 | 12 | 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 |
| -) |
19 | 13 | from opentelemetry.trace import Span
|
20 | 14 | from pydantic import BaseModel
|
21 | 15 |
|
22 |
| -trace.set_tracer_provider(TracerProvider()) |
23 |
| -trace.get_tracer_provider().add_span_processor(BatchSpanProcessor(ConsoleSpanExporter())) |
24 |
| -tracer = trace.get_tracer(__name__) |
| 16 | +from template_fastapi.opentelemetry import get_meter, get_tracer |
25 | 17 |
|
| 18 | +tracer = get_tracer(__name__) |
| 19 | +meter = get_meter(__name__) |
26 | 20 | app = FastAPI()
|
27 | 21 |
|
28 | 22 | # If APPLICATIONINSIGHTS_CONNECTION_STRING exists, configure Azure Monitor
|
@@ -189,6 +183,7 @@ async def flaky(failure_rate: int):
|
189 | 183 |
|
190 | 184 |
|
191 | 185 | # Add flaky API which raises an exception
|
| 186 | +@tracer.start_as_current_span("flaky_exception") |
192 | 187 | @app.get("/flaky/exception", tags=["flaky"], operation_id="flaky_exception")
|
193 | 188 | async def flaky_exception():
|
194 | 189 | """
|
@@ -216,9 +211,29 @@ async def heavy_sync_with_sleep(sleep_ms: int):
|
216 | 211 |
|
217 | 212 | import time
|
218 | 213 |
|
219 |
| - with tracer.start_as_current_span("foo"): |
| 214 | + with tracer.start_as_current_span("parent"): |
220 | 215 | print(f"Sleeping for {sleep_ms} milliseconds")
|
221 | 216 | time.sleep(sleep_ms / 1000.0)
|
| 217 | + with tracer.start_as_current_span("child"): |
| 218 | + print("Child span") |
222 | 219 | return {
|
223 | 220 | "message": f"Slept for {sleep_ms} milliseconds",
|
224 | 221 | }
|
| 222 | + |
| 223 | + |
| 224 | +# Add counter for dice rolls |
| 225 | +roll_counter = meter.create_counter( |
| 226 | + "dice.rolls", |
| 227 | + description="The number of rolls by roll value", |
| 228 | +) |
| 229 | + |
| 230 | + |
| 231 | +@app.get("/roll_dice", operation_id="roll_dice") |
| 232 | +async def roll_dice(): |
| 233 | + """ |
| 234 | + Simulate rolling a dice and record the roll in the meter. |
| 235 | + """ |
| 236 | + with tracer.start_as_current_span("roll_dice"): |
| 237 | + roll = random.randint(1, 6) |
| 238 | + roll_counter.add(1, {"roll.value": str(roll)}) |
| 239 | + return roll |
0 commit comments