Spaces:
Sleeping
Sleeping
| import threading | |
| import time | |
| import psutil | |
| from collections import deque | |
| import logging | |
| import os | |
| # ===== إعداد بسيط للسجل (صامت افتراضيًا) ===== | |
| VERBOSE = os.getenv("MONITOR_VERBOSE", "0") == "1" | |
| LOG_LEVEL = logging.INFO if VERBOSE else logging.WARNING | |
| logger = logging.getLogger("monitor") | |
| logger.setLevel(LOG_LEVEL) | |
| if not logger.handlers: | |
| sh = logging.StreamHandler() | |
| sh.setLevel(LOG_LEVEL) | |
| logger.addHandler(sh) | |
| # ===== مخازن المقاييس (CPU/MEM فقط) ===== | |
| cpu_history = deque(maxlen=10) | |
| mem_history = deque(maxlen=10) | |
| current_metrics = {'cpu': 0.0, 'memory': 0.0} | |
| def monitor_resources(): | |
| """تحديث نسب CPU و Memory كل 5 ثوانٍ فقط.""" | |
| logger.debug("بدأت مراقبة CPU/MEM") | |
| while True: | |
| try: | |
| # نسبة استعمال CPU للنظام كله (متوسط نصف ثانية) | |
| cpu_percent = psutil.cpu_percent(interval=0.5) | |
| # نسبة استعمال الذاكرة للنظام كله | |
| mem_percent = psutil.virtual_memory().percent | |
| # تحديث القيم الحالية والتاريخية | |
| current_metrics['cpu'] = float(cpu_percent) | |
| current_metrics['memory'] = float(mem_percent) | |
| cpu_history.append(float(cpu_percent)) | |
| mem_history.append(float(mem_percent)) | |
| if VERBOSE: | |
| logger.info(f"CPU: {cpu_percent:.1f}% | MEM: {mem_percent:.1f}%") | |
| except Exception as e: | |
| logger.exception(f"مشكلة في مراقبة الموارد: {e}") | |
| time.sleep(5) | |
| def get_current_metrics(): | |
| """تُستخدم من مسار /metrics لإرجاع القيم للواجهة.""" | |
| return { | |
| 'cpu': current_metrics['cpu'], | |
| 'memory': current_metrics['memory'], | |
| 'cpu_history': list(cpu_history), | |
| 'mem_history': list(mem_history) | |
| } | |
| def start_monitoring_thread(): | |
| """تشغيل المراقبة في خيط منفصل.""" | |
| t = threading.Thread(target=monitor_resources, daemon=True) | |
| t.start() | |
| logger.debug("تم تشغيل خيط مراقبة CPU/MEM") | |