|
8 | 8 | https://github.com/open-telemetry/opentelemetry-python-contrib/tree/main/instrumentation/opentelemetry-instrumentation-flask |
9 | 9 | """ |
10 | 10 | # mypy: disable-error-code="attr-defined" |
| 11 | +import os |
| 12 | +import fastapi |
| 13 | +import uvicorn |
| 14 | + |
11 | 15 | from azure.monitor.opentelemetry.exporter import AzureMonitorTraceExporter |
12 | | -from fastapi import Depends, FastAPI |
13 | | -from httpx import AsyncClient |
14 | 16 | from opentelemetry import trace |
| 17 | +from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor |
15 | 18 | from opentelemetry.sdk.trace import TracerProvider |
16 | 19 | from opentelemetry.sdk.trace.export import BatchSpanProcessor |
17 | 20 |
|
18 | | -app = FastAPI() |
| 21 | +# This method instruments all of the FastAPI module. |
| 22 | +# You can also use FastAPIInstrumentor().instrument_app(app) to instrument a specific app after it is created. |
| 23 | +FastAPIInstrumentor().instrument() |
| 24 | +app = fastapi.FastAPI() |
19 | 25 |
|
| 26 | +trace.set_tracer_provider(TracerProvider()) |
20 | 27 | tracer = trace.get_tracer(__name__) |
| 28 | +span_processor = BatchSpanProcessor( |
| 29 | + AzureMonitorTraceExporter.from_connection_string( |
| 30 | + os.environ["APPLICATIONINSIGHTS_CONNECTION_STRING"] |
| 31 | + ) |
| 32 | +) |
| 33 | +trace.get_tracer_provider().add_span_processor(span_processor) |
21 | 34 |
|
22 | | -async def get_client(): |
23 | | - async with AsyncClient() as client: |
24 | | - yield client |
25 | | - |
| 35 | +# Requests made to fastapi endpoints will be automatically captured |
26 | 36 | @app.get("/") |
27 | | -async def read_root(client=Depends(get_client)): |
28 | | - with tracer.start_as_current_span("read_root"): |
29 | | - response = await client.get("https://httpbin.org/get") |
30 | | - return response.json() |
| 37 | +async def test(): |
| 38 | + return {"message": "Hello World"} |
| 39 | + |
| 40 | + |
| 41 | +# Exceptions that are raised within the request are automatically captured |
| 42 | +@app.get("/exception") |
| 43 | +async def exception(): |
| 44 | + raise Exception("Hit an exception") |
| 45 | + |
| 46 | + |
| 47 | +# Set the OTEL_PYTHON_EXCLUDE_URLS environment variable to "http://127.0.0.1:8000/exclude" |
| 48 | +# Telemetry from this endpoint will not be captured due to excluded_urls config above |
| 49 | +@app.get("/exclude") |
| 50 | +async def exclude(): |
| 51 | + return {"message": "Telemetry was not captured"} |
31 | 52 |
|
32 | 53 | if __name__ == "__main__": |
33 | 54 | # cSpell:disable |
34 | | - import uvicorn |
35 | | - trace.set_tracer_provider(TracerProvider()) |
36 | | - exporter = AzureMonitorTraceExporter() |
37 | | - span_processor = BatchSpanProcessor(exporter) |
38 | | - trace.get_tracer_provider().add_span_processor(span_processor) |
39 | 55 | uvicorn.run("sample_fastapi:app", port=8008, reload=True) |
40 | 56 | # cSpell:disable |
41 | | - |
|
0 commit comments