55"""
66
77import logging
8+ import os
9+ import threading
810import time
911
1012from prometheus_client import Counter , Gauge , Histogram , start_http_server
7577 "Unix timestamp when the bot started" ,
7678)
7779
80+ active_threads = Gauge (
81+ "ris_active_threads" ,
82+ "Current number of active threads" ,
83+ )
84+
85+ memory_bytes = Gauge (
86+ "ris_memory_bytes" ,
87+ "Process RSS memory usage in bytes" ,
88+ )
89+
7890errors_total = Counter (
7991 "ris_errors_total" ,
8092 "Total uncaught errors" ,
8193 ["type" ], # exception class name
8294)
8395
8496
97+ def _collect_process_metrics ():
98+ """Periodically update thread count and memory usage."""
99+ while True :
100+ active_threads .set (threading .active_count ())
101+ try :
102+ # Read RSS from /proc/self/statm (Linux)
103+ with open ("/proc/self/statm" ) as f :
104+ pages = int (f .read ().split ()[1 ]) # resident pages
105+ memory_bytes .set (pages * os .sysconf ("SC_PAGE_SIZE" ))
106+ except (OSError , ValueError ):
107+ pass
108+ time .sleep (15 )
109+
110+
85111def start_metrics_server ():
86112 """Start the Prometheus metrics HTTP server if enabled."""
87113 if not settings .PROMETHEUS_ENABLED :
@@ -91,4 +117,9 @@ def start_metrics_server():
91117 port = settings .PROMETHEUS_PORT
92118 start_http_server (port )
93119 bot_start_time .set (time .time ())
120+
121+ # Start background thread for process metrics collection
122+ collector = threading .Thread (target = _collect_process_metrics , daemon = True )
123+ collector .start ()
124+
94125 logger .info (f"Prometheus metrics server started on port { port } " )
0 commit comments