Rifat Azad commited on
Commit
8e68bce
·
1 Parent(s): ed727a6
Files changed (1) hide show
  1. logger.py +42 -27
logger.py CHANGED
@@ -1,41 +1,56 @@
1
- from fastapi import FastAPI
2
  import psutil
3
  import time
 
 
4
 
5
  app = FastAPI()
6
 
7
- # Endpoint to get system health
8
- @app.get("/health")
9
- async def get_system_health():
 
 
 
 
 
 
 
10
  cpu_percent = psutil.cpu_percent()
11
  memory_percent = psutil.virtual_memory().percent
12
  disk_percent = psutil.disk_usage('/').percent
13
- return {
14
- "cpu_percent": cpu_percent,
15
- "memory_percent": memory_percent,
16
- "disk_percent": disk_percent
17
- }
18
-
19
- # Endpoint to get server stats
20
- start_time = time.time()
21
 
22
- @app.get("/stats")
23
- async def get_server_stats():
24
- uptime_seconds = time.time() - start_time
25
  uptime_minutes = uptime_seconds / 60
 
 
 
 
 
 
 
 
26
  return {
27
- "uptime_seconds": uptime_seconds,
28
- "uptime_minutes": uptime_minutes,
29
- # You can add more stats here like number of requests served, etc.
 
 
 
 
 
 
 
 
 
 
 
30
  }
31
 
32
- # Ping endpoint
33
- @app.get("/ping")
34
- async def ping():
35
- return {"ping": "pong"}
36
-
37
- # Root endpoint
38
- @app.get("/")
39
- async def read_root():
40
- return {"PyDVPL DISCORD BOT DOCKER"}
41
 
 
 
 
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)