Skip to content

Commit c9ea9a2

Browse files
committed
Add Open Telemetry
1 parent a420b67 commit c9ea9a2

File tree

3 files changed

+25
-1
lines changed

3 files changed

+25
-1
lines changed

code/function/fastapp/main.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
from fastapi import FastAPI
22
from fastapp.api.v1.api_v1 import api_v1_router
33
from fastapp.core.config import settings
4+
from fastapp.utils import setup_tracer
45

56

67
def get_app() -> FastAPI:
@@ -24,7 +25,7 @@ def get_app() -> FastAPI:
2425
@app.on_event("startup")
2526
async def startup_event():
2627
"""Gracefully start the application before the server reports readiness."""
27-
pass
28+
setup_tracer(app=app)
2829

2930

3031
@app.on_event("shutdown")

code/function/fastapp/utils.py

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,13 @@
11
import logging
22
from logging import Logger
33

4+
from azure.monitor.opentelemetry.exporter import AzureMonitorTraceExporter
5+
from fastapi import FastAPI
46
from fastapp.core.config import settings
7+
from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor
8+
from opentelemetry.sdk.resources import SERVICE_NAME, Resource
9+
from opentelemetry.sdk.trace import TracerProvider
10+
from opentelemetry.sdk.trace.export import BatchSpanProcessor
511

612

713
def setup_logging(module) -> Logger:
@@ -20,3 +26,18 @@ def setup_logging(module) -> Logger:
2026
)
2127
logger.addHandler(logger_stream_handler)
2228
return logger
29+
30+
31+
def setup_tracer(app: FastAPI):
32+
"""Setup tracer for Open Telemetry.
33+
34+
app (FastAPI): The app to be instrumented by Open Telemetry.
35+
RETURNS (None): Nothing is being returned.
36+
"""
37+
if settings.APPLICATIONINSIGHTS_CONNECTION_STRING:
38+
exporter = AzureMonitorTraceExporter.from_connection_string(
39+
settings.APPLICATIONINSIGHTS_CONNECTION_STRING
40+
)
41+
tracer = TracerProvider(resource=Resource({SERVICE_NAME: "api"}))
42+
tracer.add_span_processor(BatchSpanProcessor(exporter))
43+
FastAPIInstrumentor.instrument_app(app, tracer_provider=tracer)

code/function/requirements.txt

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,3 +5,5 @@
55
azure-functions~=1.14.0
66
fastapi~=0.96.1
77
aiohttp~=3.8.4
8+
opentelemetry-instrumentation-fastapi==0.39b0
9+
azure-monitor-opentelemetry-exporter==1.0.0b14

0 commit comments

Comments
 (0)