Spaces:
Sleeping
Sleeping
Claude Code Claude Code commited on
Commit ·
9a6065d
1
Parent(s): b4b8c2c
Claude Code: Add /metrics endpoint with psutil for CPU, memory, disk usage
Browse files
app.py
CHANGED
|
@@ -69,6 +69,44 @@ def get_app():
|
|
| 69 |
"active_agents": 1 # Cain is always active
|
| 70 |
}
|
| 71 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 72 |
@app.exception_handler(Exception)
|
| 73 |
async def global_exception_handler(request: Request, exc: Exception):
|
| 74 |
"""Global exception handler to catch all errors."""
|
|
|
|
| 69 |
"active_agents": 1 # Cain is always active
|
| 70 |
}
|
| 71 |
|
| 72 |
+
@app.get("/metrics")
|
| 73 |
+
async def metrics():
|
| 74 |
+
"""System metrics endpoint with CPU, memory, and disk usage."""
|
| 75 |
+
try:
|
| 76 |
+
import psutil
|
| 77 |
+
except ImportError:
|
| 78 |
+
return JSONResponse(
|
| 79 |
+
status_code=503,
|
| 80 |
+
content={"error": "psutil not installed", "message": "System metrics unavailable"}
|
| 81 |
+
)
|
| 82 |
+
|
| 83 |
+
try:
|
| 84 |
+
cpu_percent = psutil.cpu_percent(interval=0.1)
|
| 85 |
+
memory = psutil.virtual_memory()
|
| 86 |
+
disk = psutil.disk_usage('/')
|
| 87 |
+
|
| 88 |
+
return {
|
| 89 |
+
"cpu_percent": cpu_percent,
|
| 90 |
+
"memory": {
|
| 91 |
+
"percent": memory.percent,
|
| 92 |
+
"total_gb": round(memory.total / (1024**3), 2),
|
| 93 |
+
"used_gb": round(memory.used / (1024**3), 2),
|
| 94 |
+
"available_gb": round(memory.available / (1024**3), 2)
|
| 95 |
+
},
|
| 96 |
+
"disk": {
|
| 97 |
+
"percent": disk.percent,
|
| 98 |
+
"total_gb": round(disk.total / (1024**3), 2),
|
| 99 |
+
"used_gb": round(disk.used / (1024**3), 2),
|
| 100 |
+
"free_gb": round(disk.free / (1024**3), 2)
|
| 101 |
+
}
|
| 102 |
+
}
|
| 103 |
+
except Exception as e:
|
| 104 |
+
logger.error(f"Error collecting metrics: {e}")
|
| 105 |
+
return JSONResponse(
|
| 106 |
+
status_code=500,
|
| 107 |
+
content={"error": "Failed to collect metrics", "message": str(e)}
|
| 108 |
+
)
|
| 109 |
+
|
| 110 |
@app.exception_handler(Exception)
|
| 111 |
async def global_exception_handler(request: Request, exc: Exception):
|
| 112 |
"""Global exception handler to catch all errors."""
|