|
| 1 | +from flask import blueprints |
| 2 | +from werkzeug.middleware.dispatcher import DispatcherMiddleware |
| 3 | +from prometheus_client import make_wsgi_app, Counter, Gauge |
| 4 | +import threading |
| 5 | +import time |
| 6 | +from src.config import app |
| 7 | +from src.utils import _get_system_info |
| 8 | + |
| 9 | +# Define the Prometheus Blueprint |
| 10 | +prometheus_bp = blueprints.Blueprint('prometheus', __name__) |
| 11 | + |
| 12 | +# Initialize Prometheus metrics |
| 13 | +cpu_usage_metric = Gauge('cpu_usage_percentage', 'Current CPU usage percentage') |
| 14 | +memory_usage_metric = Gauge('memory_usage_percentage', 'Current memory usage percentage') |
| 15 | +disk_usage_metric = Gauge('disk_usage_percentage', 'Disk usage percentage') |
| 16 | +network_sent_metric = Gauge('network_bytes_sent', 'Total network bytes sent') |
| 17 | +network_recv_metric = Gauge('network_bytes_received', 'Total network bytes received') |
| 18 | +request_count = Counter('http_requests_total', 'Total HTTP requests made') |
| 19 | + |
| 20 | +def collect_metrics(): |
| 21 | + """ |
| 22 | + Collect system metrics and update Prometheus Gauges. |
| 23 | + Runs in a separate thread and updates metrics every 5 seconds. |
| 24 | + """ |
| 25 | + 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() |
| 38 | + |
| 39 | + # Sleep for 5 seconds before the next collection |
| 40 | + time.sleep(5) |
| 41 | + |
| 42 | +# Start the metrics collection in a background thread |
| 43 | +metrics_thread = threading.Thread(target=collect_metrics, daemon=True) |
| 44 | +metrics_thread.start() |
| 45 | + |
| 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 | +}) |
0 commit comments