Rifat Azad commited on
Commit
942d992
·
1 Parent(s): 8e68bce
Files changed (1) hide show
  1. logger.py +18 -45
logger.py CHANGED
@@ -1,56 +1,29 @@
1
- from fastapi import FastAPI, Request
2
  import psutil
3
- import time
4
- import subprocess
5
- import asyncio
6
 
7
  app = FastAPI()
8
 
9
- # Function to ping google.com
10
- def ping_google():
11
- result = subprocess.run(['ping', '-c', '4', 'google.com'], capture_output=True, text=True)
12
- return result.stdout
13
-
14
- # Endpoint to get system health, stats, and ping
15
  @app.get("/")
16
- async def root(request: Request):
17
- start_time = time.time() # Start measuring time
18
- # System health
 
 
19
  cpu_percent = psutil.cpu_percent()
20
  memory_percent = psutil.virtual_memory().percent
21
- disk_percent = psutil.disk_usage('/').percent
22
-
23
- # Server stats
24
- uptime_seconds = time.time() - app.state.start_time
25
- uptime_minutes = uptime_seconds / 60
26
-
27
- # Ping
28
- ping_result = ping_google()
29
 
30
- # Calculate ping latency
31
- end_time = time.time()
32
- ping_latency = (end_time - start_time) * 1000 # Convert to milliseconds
 
 
 
 
33
 
34
  return {
35
- "system_health": {
36
- "cpu_percent": cpu_percent,
37
- "memory_percent": memory_percent,
38
- "disk_percent": disk_percent
39
- },
40
- "server_stats": {
41
- "uptime_seconds": uptime_seconds,
42
- "uptime_minutes": uptime_minutes
43
- # Add more stats here if needed
44
- },
45
- "ping": {
46
- "status": ping_result,
47
- "latency_ms": ping_latency
48
- }
49
  }
50
-
51
- # Define startup event handler
52
- async def startup_event():
53
- app.state.start_time = time.time() # Initialize server start time
54
-
55
- # Register the startup event handler using add_event_handler
56
- app.add_event_handler("startup", startup_event)
 
1
+ from fastapi import FastAPI
2
  import psutil
3
+ import httpx
 
 
4
 
5
  app = FastAPI()
6
 
 
 
 
 
 
 
7
  @app.get("/")
8
+ async def read_root():
9
+ # Get system uptime
10
+ uptime = psutil.boot_time()
11
+
12
+ # Get system vitals
13
  cpu_percent = psutil.cpu_percent()
14
  memory_percent = psutil.virtual_memory().percent
 
 
 
 
 
 
 
 
15
 
16
+ # Measure latency to google.com
17
+ async with httpx.AsyncClient() as client:
18
+ try:
19
+ response = await client.get("https://www.google.com")
20
+ latency = response.elapsed.total_seconds()
21
+ except httpx.RequestError:
22
+ latency = "Error: Unable to connect to google.com"
23
 
24
  return {
25
+ "System Uptime": uptime,
26
+ "CPU Usage": f"{cpu_percent}%",
27
+ "Memory Usage": f"{memory_percent}%",
28
+ "Latency to Google": latency
 
 
 
 
 
 
 
 
 
 
29
  }