Skip to content

Commit

Permalink
Update FastAPI sample with instrumentation
Browse files Browse the repository at this point in the history
  • Loading branch information
jeremydvoss committed Mar 12, 2024
1 parent b417ceb commit dff0961
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 17 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -8,34 +8,36 @@
https://github.com/open-telemetry/opentelemetry-python-contrib/tree/main/instrumentation/opentelemetry-instrumentation-flask
"""
# mypy: disable-error-code="attr-defined"
import os
import fastapi
import uvicorn

from azure.monitor.opentelemetry.exporter import AzureMonitorTraceExporter
from fastapi import Depends, FastAPI
from httpx import AsyncClient
from opentelemetry import trace
from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor

app = FastAPI()
# This method instruments all of the FastAPI module.
# You can also use FastAPIInstrumentor().instrument_app(app) to instrument a specific app after it is created.
FastAPIInstrumentor().instrument()
app = fastapi.FastAPI()

trace.set_tracer_provider(TracerProvider())
tracer = trace.get_tracer(__name__)

async def get_client():
async with AsyncClient() as client:
yield client
span_processor = BatchSpanProcessor(
AzureMonitorTraceExporter.from_connection_string(
os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"]
)
)
trace.get_tracer_provider().add_span_processor(span_processor)

@app.get("/")
async def read_root(client=Depends(get_client)):
with tracer.start_as_current_span("read_root"):
response = await client.get("https://httpbin.org/get")
return response.json()
async def index(request: fastapi.Request):
return {"Test FastAPI request"}

if __name__ == "__main__":
# cSpell:disable
import uvicorn
trace.set_tracer_provider(TracerProvider())
exporter = AzureMonitorTraceExporter()
span_processor = BatchSpanProcessor(exporter)
trace.get_tracer_provider().add_span_processor(span_processor)
uvicorn.run("sample_fastapi:app", port=8008, reload=True)
# cSpell:disable

Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@

from azure.monitor.opentelemetry.exporter import AzureMonitorTraceExporter

# Enable instrumentation in the flask library.
# This method instruments all of FastAPI.
# You can also use FlaskInstrumentor().instrument_app(app) to instrument a specific app after it is created.
FlaskInstrumentor().instrument()
app = flask.Flask(__name__)

Expand Down

0 comments on commit dff0961

Please sign in to comment.