gogo2/monitor_dashboard.py
2025-05-26 16:02:40 +03:00

172 lines
6.2 KiB
Python

#!/usr/bin/env python3
"""
Dashboard Performance Monitor
This script monitors the running scalping dashboard for:
- Response time
- Error detection
- Memory usage
- Trade activity
- WebSocket connectivity
"""
import requests
import time
import logging
import psutil
import json
from datetime import datetime
# Setup logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
def check_dashboard_status():
"""Check if dashboard is responding"""
try:
start_time = time.time()
response = requests.get("http://127.0.0.1:8051", timeout=5)
response_time = (time.time() - start_time) * 1000
if response.status_code == 200:
logger.info(f"✅ Dashboard responding - {response_time:.1f}ms")
return True, response_time
else:
logger.error(f"❌ Dashboard returned status {response.status_code}")
return False, response_time
except Exception as e:
logger.error(f"❌ Dashboard connection failed: {e}")
return False, 0
def check_system_resources():
"""Check system resource usage"""
try:
# Find Python processes (our dashboard)
python_processes = []
for proc in psutil.process_iter(['pid', 'name', 'memory_info', 'cpu_percent']):
if 'python' in proc.info['name'].lower():
python_processes.append(proc)
total_memory = sum(proc.info['memory_info'].rss for proc in python_processes) / 1024 / 1024
total_cpu = sum(proc.info['cpu_percent'] for proc in python_processes)
logger.info(f"📊 System Resources:")
logger.info(f" • Python Processes: {len(python_processes)}")
logger.info(f" • Total Memory: {total_memory:.1f} MB")
logger.info(f" • Total CPU: {total_cpu:.1f}%")
return len(python_processes), total_memory, total_cpu
except Exception as e:
logger.error(f"❌ Failed to check system resources: {e}")
return 0, 0, 0
def check_log_for_errors():
"""Check recent logs for errors"""
try:
import os
log_file = "logs/enhanced_trading.log"
if not os.path.exists(log_file):
logger.warning("❌ Log file not found")
return 0, 0
# Read last 100 lines
with open(log_file, 'r', encoding='utf-8') as f:
lines = f.readlines()
recent_lines = lines[-100:] if len(lines) > 100 else lines
error_count = sum(1 for line in recent_lines if 'ERROR' in line)
warning_count = sum(1 for line in recent_lines if 'WARNING' in line)
if error_count > 0:
logger.warning(f"⚠️ Found {error_count} errors in recent logs")
if warning_count > 0:
logger.info(f"⚠️ Found {warning_count} warnings in recent logs")
return error_count, warning_count
except Exception as e:
logger.error(f"❌ Failed to check logs: {e}")
return 0, 0
def check_trading_activity():
"""Check for recent trading activity"""
try:
import os
import glob
# Look for trade log files
trade_files = glob.glob("trade_logs/session_*.json")
if trade_files:
latest_file = max(trade_files, key=os.path.getctime)
file_size = os.path.getsize(latest_file)
file_time = datetime.fromtimestamp(os.path.getctime(latest_file))
logger.info(f"📈 Trading Activity:")
logger.info(f" • Latest Session: {os.path.basename(latest_file)}")
logger.info(f" • Log Size: {file_size} bytes")
logger.info(f" • Last Update: {file_time.strftime('%H:%M:%S')}")
return len(trade_files), file_size
else:
logger.info("📈 No trading session files found yet")
return 0, 0
except Exception as e:
logger.error(f"❌ Failed to check trading activity: {e}")
return 0, 0
def main():
"""Main monitoring loop"""
logger.info("🔍 STARTING DASHBOARD PERFORMANCE MONITOR")
logger.info("=" * 60)
monitor_count = 0
try:
while True:
monitor_count += 1
logger.info(f"\n🔄 Monitor Check #{monitor_count} - {datetime.now().strftime('%H:%M:%S')}")
logger.info("-" * 40)
# Check dashboard status
is_responding, response_time = check_dashboard_status()
# Check system resources
proc_count, memory_mb, cpu_percent = check_system_resources()
# Check for errors
error_count, warning_count = check_log_for_errors()
# Check trading activity
session_count, log_size = check_trading_activity()
# Summary
logger.info(f"\n📋 MONITOR SUMMARY:")
logger.info(f" • Dashboard: {'✅ OK' if is_responding else '❌ DOWN'} ({response_time:.1f}ms)")
logger.info(f" • Processes: {proc_count} running")
logger.info(f" • Memory: {memory_mb:.1f} MB")
logger.info(f" • CPU: {cpu_percent:.1f}%")
logger.info(f" • Errors: {error_count} | Warnings: {warning_count}")
logger.info(f" • Sessions: {session_count} | Latest Log: {log_size} bytes")
# Performance assessment
if is_responding and error_count == 0:
if response_time < 1000 and memory_mb < 2000:
logger.info("🎯 PERFORMANCE: EXCELLENT")
elif response_time < 2000 and memory_mb < 4000:
logger.info("✅ PERFORMANCE: GOOD")
else:
logger.info("⚠️ PERFORMANCE: MODERATE")
else:
logger.error("❌ PERFORMANCE: POOR")
# Wait before next check
time.sleep(30) # Check every 30 seconds
except KeyboardInterrupt:
logger.info("\n👋 Monitor stopped by user")
except Exception as e:
logger.error(f"❌ Monitor failed: {e}")
if __name__ == "__main__":
main()