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
@@ -40,6 +34,7 @@ def server_request_hook(span: Span, scope: dict):
40
34
41
35
configure_azure_monitor (
42
36
connection_string = AZURE_CONNECTION_STRING ,
37
+ # enable_live_metrics=True,
43
38
server_request_hook = server_request_hook ,
44
39
)
45
40
FastAPIInstrumentor .instrument_app (app )
@@ -188,6 +183,7 @@ async def flaky(failure_rate: int):
188
183
189
184
190
185
# Add flaky API which raises an exception
186
+ @tracer .start_as_current_span ("flaky_exception" )
191
187
@app .get ("/flaky/exception" , tags = ["flaky" ], operation_id = "flaky_exception" )
192
188
async def flaky_exception ():
193
189
"""
@@ -215,9 +211,29 @@ async def heavy_sync_with_sleep(sleep_ms: int):
215
211
216
212
import time
217
213
218
- with tracer .start_as_current_span ("foo " ):
214
+ with tracer .start_as_current_span ("parent " ):
219
215
print (f"Sleeping for { sleep_ms } milliseconds" )
220
216
time .sleep (sleep_ms / 1000.0 )
217
+ with tracer .start_as_current_span ("child" ):
218
+ print ("Child span" )
221
219
return {
222
220
"message" : f"Slept for { sleep_ms } milliseconds" ,
223
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