1- from flask import blueprints
2- from werkzeug .middleware .dispatcher import DispatcherMiddleware
3- from prometheus_client import make_wsgi_app , Counter , Gauge
1+ from flask import Blueprint , Response
2+ from prometheus_client import Counter , Gauge , generate_latest
43import threading
54import time
65from src .config import app
76from src .utils import _get_system_info
87
98# Define the Prometheus Blueprint
10- prometheus_bp = blueprints . Blueprint ('prometheus' , __name__ )
9+ prometheus_bp = Blueprint ('prometheus' , __name__ )
1110
1211# Initialize Prometheus metrics
1312cpu_usage_metric = Gauge ('cpu_usage_percentage' , 'Current CPU usage percentage' )
@@ -23,27 +22,30 @@ def collect_metrics():
2322 Runs in a separate thread and updates metrics every 5 seconds.
2423 """
2524 while True :
26- # Gather system information
27- system_info = _get_system_info ()
28-
29- # Update Prometheus metrics
30- cpu_usage_metric .set (system_info ['cpu_percent' ])
31- memory_usage_metric .set (system_info ['memory_percent' ])
32- disk_usage_metric .set (system_info ['disk_percent' ])
33- network_sent_metric .set (system_info ['network_sent' ])
34- network_recv_metric .set (system_info ['network_received' ])
35-
36- # Increment HTTP request counter
37- request_count .inc ()
25+ try :
26+ # Gather system information
27+ system_info = _get_system_info ()
28+
29+ # Update Prometheus metrics
30+ cpu_usage_metric .set (system_info ['cpu_percent' ])
31+ memory_usage_metric .set (system_info ['memory_percent' ])
32+ disk_usage_metric .set (system_info ['disk_percent' ])
33+ network_sent_metric .set (system_info ['network_sent' ])
34+ network_recv_metric .set (system_info ['network_received' ])
35+
36+ # Increment HTTP request counter
37+ request_count .inc ()
38+ except Exception as e :
39+ print (f"Error collecting metrics: { e } " )
3840
3941 # Sleep for 5 seconds before the next collection
40- time .sleep (5 )
42+ time .sleep (10 )
4143
4244# Start the metrics collection in a background thread
4345metrics_thread = threading .Thread (target = collect_metrics , daemon = True )
4446metrics_thread .start ()
4547
46- # Expose the /metrics endpoint for Prometheus to scrape metrics
47- app .wsgi_app = DispatcherMiddleware ( app . wsgi_app , {
48- '/ metrics' : make_wsgi_app () # Serve Prometheus metrics at /metrics
49- } )
48+ # Define a route to serve Prometheus metrics
49+ @ app .route ( '/metrics' )
50+ def metrics ():
51+ return Response ( generate_latest (), mimetype = 'text/plain' )
0 commit comments