ayb-bh1146 commited on
Commit
27cb8fd
·
verified ·
1 Parent(s): 7d0e12b

Create middleware/metrics.py

Browse files
Files changed (1) hide show
  1. middleware/metrics.py +25 -0
middleware/metrics.py ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import time
2
+ from functools import wraps
3
+ from flask import request
4
+
5
+ REQUESTS_TOTAL = {}
6
+ REQUEST_DURATION = {}
7
+
8
+ def track_request(f):
9
+ @wraps(f)
10
+ def wrapper(*args, **kwargs):
11
+ start = time.time()
12
+ try:
13
+ response = f(*args, **kwargs)
14
+ return response
15
+ finally:
16
+ duration = time.time() - start
17
+ endpoint = request.path
18
+ if endpoint not in REQUEST_DURATION:
19
+ REQUEST_DURATION[endpoint] = []
20
+ REQUEST_DURATION[endpoint].append(duration)
21
+ REQUESTS_TOTAL[endpoint] = REQUESTS_TOTAL.get(endpoint, 0) + 1
22
+ return wrapper
23
+
24
+ def get_metrics():
25
+ return {"total_requests": REQUESTS_TOTAL, "avg_duration": {k: sum(v)/len(v) for k, v in REQUEST_DURATION.items()}}