Skip to content

Commit 917565d

Browse files
author
ks6088ts
committed
add trace impl
1 parent 867eaab commit 917565d

File tree

2 files changed

+35
-0
lines changed

2 files changed

+35
-0
lines changed

docs/index.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,3 +21,4 @@
2121
- [Application Insights の概要 - OpenTelemetry の可観測性](https://learn.microsoft.com/ja-jp/azure/azure-monitor/app/app-insights-overview)
2222
- [FastAPI のテレメトリデータを Azure Application Insights に送る](https://qiita.com/hoto17296/items/2f366dfabdbe3d1d4e97)
2323
- [【Azure Functions】 - Application Insights のログが表示されない問題](https://zenn.dev/headwaters/articles/ff19f7e1b99b44)
24+
- [opentelemetry-instrumentation-fastapi (python) から OpenTelemetry に入門する](https://zenn.dev/taxin/articles/opentelemetry-fast-api-instrumentation-basics)

template_fastapi/app.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,10 +9,20 @@
99

1010
from azure.monitor.opentelemetry import configure_azure_monitor
1111
from fastapi import FastAPI, HTTPException, Query
12+
from opentelemetry import trace
1213
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+
)
1319
from opentelemetry.trace import Span
1420
from pydantic import BaseModel
1521

22+
trace.set_tracer_provider(TracerProvider())
23+
trace.get_tracer_provider().add_span_processor(BatchSpanProcessor(ConsoleSpanExporter()))
24+
tracer = trace.get_tracer(__name__)
25+
1626
app = FastAPI()
1727

1828
# If APPLICATIONINSIGHTS_CONNECTION_STRING exists, configure Azure Monitor
@@ -187,3 +197,27 @@ async def flaky_exception():
187197
status_code=500,
188198
detail="Simulated exception",
189199
)
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

Comments
 (0)