Download src/api/monitoring_dashboard.py from anaselamr/yaz: direct link, hf CLI and curl.
- Browser
- Download file 7.16 kB
-
https://huggingface.co/spaces/anaselamr/yaz/resolve/main/src/api/monitoring_dashboard.py
- Command line
-
hf download hf://spaces/anaselamr/yaz/src/api/monitoring_dashboard.py
-
curl -L -o monitoring_dashboard.py https://huggingface.co/spaces/anaselamr/yaz/resolve/main/src/api/monitoring_dashboard.py
7.16 kB
| """ | |
| YAZ Care Platform - Monitoring Dashboard API | |
| Real-time metrics and system health visualization | |
| """ | |
| from typing import Dict, Any, List, Optional | |
| from datetime import datetime, timedelta, timezone | |
| from collections import defaultdict | |
| import structlog | |
| from fastapi import APIRouter, Query | |
| from pydantic import BaseModel | |
| logger = structlog.get_logger(__name__) | |
| router = APIRouter(prefix="/api/monitoring", tags=["Monitoring"]) | |
| class MetricPoint(BaseModel): | |
| """Single metric data point""" | |
| timestamp: str | |
| value: float | |
| labels: Optional[Dict[str, str]] = None | |
| class MetricSeries(BaseModel): | |
| """Time series of metric data""" | |
| name: str | |
| description: str | |
| unit: str | |
| data_points: List[MetricPoint] | |
| class DashboardStats(BaseModel): | |
| """Dashboard summary statistics""" | |
| total_requests: int | |
| total_errors: int | |
| error_rate: float | |
| avg_response_time_ms: float | |
| active_requests: int | |
| uptime_seconds: int | |
| timestamp: str | |
| class SystemHealth(BaseModel): | |
| """System health summary""" | |
| status: str | |
| database: str | |
| redis: str | |
| cpu_percent: float | |
| memory_percent: float | |
| disk_percent: float | |
| async def get_dashboard_data( | |
| time_range: str = Query("1h", description="Time range: 1h, 6h, 24h, 7d") | |
| ): | |
| """ | |
| Get comprehensive monitoring dashboard data | |
| Returns real-time metrics, system health, and performance statistics | |
| """ | |
| # Mock data - in production, fetch from Prometheus or time-series DB | |
| dashboard_data = { | |
| "timestamp": datetime.now(timezone.utc).isoformat(), | |
| "time_range": time_range, | |
| "stats": { | |
| "total_requests": 15234, | |
| "total_errors": 42, | |
| "error_rate": 0.28, | |
| "avg_response_time_ms": 45.3, | |
| "active_requests": 3, | |
| "uptime_seconds": 86400 | |
| }, | |
| "health": { | |
| "status": "healthy", | |
| "database": "connected", | |
| "redis": "connected", | |
| "cpu_percent": 23.5, | |
| "memory_percent": 45.2, | |
| "disk_percent": 62.1 | |
| }, | |
| "request_rate": { | |
| "current": 125.5, | |
| "peak": 342.1, | |
| "average": 178.3 | |
| }, | |
| "endpoints": [ | |
| {"path": "/api/health", "requests": 3421, "avg_ms": 12.3, "error_rate": 0.0}, | |
| {"path": "/api/surgio/health", "requests": 2156, "avg_ms": 18.7, "error_rate": 0.1}, | |
| {"path": "/api/clinica/health", "requests": 1987, "avg_ms": 21.4, "error_rate": 0.0}, | |
| {"path": "/apps/labo/", "requests": 1543, "avg_ms": 35.2, "error_rate": 0.2} | |
| ], | |
| "alerts": [] | |
| } | |
| return dashboard_data | |
| async def get_request_metrics( | |
| interval: str = Query("5m", description="Data interval: 1m, 5m, 15m, 1h") | |
| ): | |
| """Get HTTP request metrics over time""" | |
| # Generate mock time series data | |
| now = datetime.now(timezone.utc) | |
| points = [] | |
| for i in range(12): | |
| timestamp = now - timedelta(minutes=5 * (11 - i)) | |
| points.append({ | |
| "timestamp": timestamp.isoformat(), | |
| "requests": 150 + (i * 10), | |
| "errors": 2 + (i % 3), | |
| "avg_response_ms": 45.3 + (i * 2.1) | |
| }) | |
| return { | |
| "interval": interval, | |
| "data_points": points | |
| } | |
| async def get_performance_metrics(): | |
| """Get system performance metrics""" | |
| return { | |
| "timestamp": datetime.now(timezone.utc).isoformat(), | |
| "cpu": { | |
| "current": 23.5, | |
| "average": 28.3, | |
| "peak": 67.2 | |
| }, | |
| "memory": { | |
| "current": 45.2, | |
| "average": 42.8, | |
| "peak": 58.9, | |
| "total_mb": 8192, | |
| "used_mb": 3702 | |
| }, | |
| "database": { | |
| "connections": 15, | |
| "max_connections": 100, | |
| "pool_usage_percent": 15.0, | |
| "avg_query_ms": 8.3 | |
| }, | |
| "cache": { | |
| "hit_rate": 87.5, | |
| "size_mb": 245, | |
| "max_size_mb": 1024 | |
| } | |
| } | |
| async def get_error_metrics( | |
| hours: int = Query(24, description="Number of hours to look back") | |
| ): | |
| """Get error metrics and trends""" | |
| return { | |
| "timestamp": datetime.now(timezone.utc).isoformat(), | |
| "period_hours": hours, | |
| "summary": { | |
| "total_errors": 42, | |
| "error_rate": 0.28, | |
| "critical_errors": 2, | |
| "warnings": 15 | |
| }, | |
| "by_category": [ | |
| {"category": "validation_error", "count": 18, "percent": 42.9}, | |
| {"category": "not_found_error", "count": 12, "percent": 28.6}, | |
| {"category": "authentication_error", "count": 8, "percent": 19.0}, | |
| {"category": "internal_server_error", "count": 4, "percent": 9.5} | |
| ], | |
| "recent_errors": [ | |
| { | |
| "timestamp": (datetime.now(timezone.utc) - timedelta(minutes=15)).isoformat(), | |
| "category": "validation_error", | |
| "message": "Invalid UUID format for patient_id", | |
| "endpoint": "/api/surgio/surgeries" | |
| }, | |
| { | |
| "timestamp": (datetime.now(timezone.utc) - timedelta(hours=2)).isoformat(), | |
| "category": "not_found_error", | |
| "message": "Resource not found", | |
| "endpoint": "/api/admin/stats" | |
| } | |
| ] | |
| } | |
| async def get_module_metrics(): | |
| """Get per-module metrics""" | |
| modules = [ | |
| { | |
| "name": "surgio", | |
| "status": "healthy", | |
| "requests_total": 4523, | |
| "avg_response_ms": 38.5, | |
| "error_rate": 0.15, | |
| "active_operations": 7 | |
| }, | |
| { | |
| "name": "clinica", | |
| "status": "healthy", | |
| "requests_total": 3891, | |
| "avg_response_ms": 42.1, | |
| "error_rate": 0.08, | |
| "active_operations": 12 | |
| }, | |
| { | |
| "name": "labo", | |
| "status": "healthy", | |
| "requests_total": 2156, | |
| "avg_response_ms": 55.3, | |
| "error_rate": 0.23, | |
| "active_operations": 5 | |
| }, | |
| { | |
| "name": "pharma", | |
| "status": "healthy", | |
| "requests_total": 1678, | |
| "avg_response_ms": 48.7, | |
| "error_rate": 0.12, | |
| "active_operations": 3 | |
| } | |
| ] | |
| return { | |
| "timestamp": datetime.now(timezone.utc).isoformat(), | |
| "modules": modules | |
| } | |
| async def get_active_alerts(): | |
| """Get active system alerts""" | |
| return { | |
| "timestamp": datetime.now(timezone.utc).isoformat(), | |
| "total_alerts": 0, | |
| "critical": 0, | |
| "warning": 0, | |
| "info": 0, | |
| "alerts": [] | |
| } | |
| __all__ = ["router"] | |