Skip to content

Commit 64daa62

Browse files
committed
feat(metrics): add bot health metrics
- Track active thread count (sampled every 15s) - Track RSS memory usage from /proc/self/statm - Bot start timestamp gauge (for uptime calculation)
1 parent c524b03 commit 64daa62

2 files changed

Lines changed: 42 additions & 0 deletions

File tree

reverse_image_search_bot/metrics.py

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@
55
"""
66

77
import logging
8+
import os
9+
import threading
810
import time
911

1012
from prometheus_client import Counter, Gauge, Histogram, start_http_server
@@ -75,13 +77,37 @@
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+
7890
errors_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+
85111
def 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}")

uv.lock

Lines changed: 11 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

0 commit comments

Comments
 (0)