-
Notifications
You must be signed in to change notification settings - Fork 3
/
observability.py
156 lines (138 loc) · 5.19 KB
/
observability.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
"""
Observability definition
Code from https://github.com/Blueswen/fastapi-observability
"""
import logging
import logging.config
import time
from typing import Tuple
from opentelemetry import trace
from opentelemetry.sdk.trace import TracerProvider
from opentelemetry.sdk.trace.export import BatchSpanProcessor
from opentelemetry.sdk.resources import Resource
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
from opentelemetry.instrumentation.logging import LoggingInstrumentor
from starlette.types import ASGIApp
from starlette.requests import Request
from starlette.responses import Response
from starlette.routing import Match
from starlette.status import HTTP_500_INTERNAL_SERVER_ERROR
from starlette.middleware.base import (
BaseHTTPMiddleware,
RequestResponseEndpoint
)
from prometheus_client import (
REGISTRY,
Counter,
Gauge,
Histogram
)
from prometheus_client.openmetrics.exposition import (
CONTENT_TYPE_LATEST,
generate_latest
)
import settings
INFO = Gauge(
"fastapi_app_info", "FastAPI application information.", [
"app_name"]
)
REQUESTS = Counter(
"fastapi_requests_total", "Total count of requests by method and path.", [
"method", "path", "app_name"]
)
RESPONSES = Counter(
"fastapi_responses_total",
"Total count of responses by method, path and status codes.",
["method", "path", "status_code", "app_name"],
)
REQUESTS_PROCESSING_TIME = Histogram(
"fastapi_requests_duration_seconds",
"Histogram of requests processing time by path (in seconds)",
["method", "path", "app_name"],
)
EXCEPTIONS = Counter(
"fastapi_exceptions_total",
"Total count of exceptions raised by path and exception type",
["method", "path", "exception_type", "app_name"],
)
REQUESTS_IN_PROGRESS = Gauge(
"fastapi_requests_in_progress",
"Gauge of requests by method and path currently being processed",
["method", "path", "app_name"],
)
logging.config.dictConfig(settings.LOGGING)
LOGGER = logging.getLogger(settings.APP_NAME)
class PrometheusMiddleware(BaseHTTPMiddleware):
"""Add function to HTTP Middleware"""
def __init__(self, app: ASGIApp, app_name: str = "fastapi-app") -> None:
"""Init middleware"""
super().__init__(app)
self.app_name = app_name
INFO.labels(app_name=self.app_name).inc()
async def dispatch(self, request: Request, call_next: RequestResponseEndpoint) -> Response:
"""Add Metrics informations"""
method = request.method
path, is_handled_path = self.get_path(request)
response_status_code = 0
if not is_handled_path:
return await call_next(request)
REQUESTS_IN_PROGRESS.labels(
method=method, path=path, app_name=self.app_name).inc()
REQUESTS.labels(method=method, path=path, app_name=self.app_name).inc()
before_time = time.perf_counter()
try:
response = await call_next(request)
except BaseException as e:
response_status_code = HTTP_500_INTERNAL_SERVER_ERROR
EXCEPTIONS.labels(method=method, path=path, exception_type=type(
e).__name__, app_name=self.app_name).inc()
raise e from None
else:
response_status_code = response.status_code
after_time = time.perf_counter()
# retrieve trace id for exemplar
span = trace.get_current_span()
trace_id = trace.format_trace_id(
span.get_span_context().trace_id)
REQUESTS_PROCESSING_TIME.labels(method=method, path=path, app_name=self.app_name)\
.observe(
after_time - before_time, exemplar={'TraceID': trace_id}
)
finally:
RESPONSES.labels(method=method, path=path,
status_code=response_status_code, app_name=self.app_name).inc()
REQUESTS_IN_PROGRESS.labels(
method=method, path=path, app_name=self.app_name).dec()
return response
@staticmethod
def get_path(request: Request) -> Tuple[str, bool]:
"""Function to check request.path and authorize"""
for route in request.app.routes:
match, _ = route.matches(request.scope)
if match == Match.FULL:
return route.path, True
return request.url.path, False
def metrics(request: Request) -> Response:
"""Metrics configuration"""
return Response(generate_latest(REGISTRY), headers={"Content-Type": CONTENT_TYPE_LATEST})
def setting_otlp() -> TracerProvider():
"""Traces configuration"""
resource = Resource(attributes={
"service.name": settings.APP_NAME,
"job": "Backend",
"host": "FastAPI",
"agent": "OTel"
})
# Set the trace provider
tracer = TracerProvider(resource=resource)
trace.set_tracer_provider(tracer)
otlp_exporter = OTLPSpanExporter(endpoint="{0}://{1}:{2}{3}".format(
settings.OTEL_PROTOCOL,
settings.OTEL_HOST,
settings.OTEL_PORT,
settings.OTEL_PATH)
)
tracer.add_span_processor(BatchSpanProcessor(otlp_exporter))
LoggingInstrumentor().instrument(set_logging_format=True)
return tracer
tracer = setting_otlp()