مقدمه
Prometheus exporter ها برنامههایی هستند که معیارها را در قالب متنی Prometheus در معرض قرار میدهند. در حالی که صدها exporter برای سیستمهای رایج وجود دارد، اغلب نیاز دارید اپلیکیشنهای سفارشی یا معیارهای کسبوکار را پایش کنید.
نوشتن Exporter با Python
PYTHON
from prometheus_client import start_http_server, Counter, Gauge, Histogram
import time, requests
REQUEST_COUNT = Counter('myapp_requests_total', 'Total requests', ['endpoint', 'status'])
ACTIVE_USERS = Gauge('myapp_active_users', 'Active users')
RESPONSE_TIME = Histogram('myapp_response_seconds', 'Response time', ['endpoint'])
def collect_metrics():
try:
start = time.time()
data = requests.get('http://myapp:8080/internal/stats', timeout=5).json()
RESPONSE_TIME.labels(endpoint='/stats').observe(time.time() - start)
ACTIVE_USERS.set(data['active_users'])
except Exception as e:
REQUEST_COUNT.labels(endpoint='/stats', status='error').inc()
if __name__ == '__main__':
start_http_server(9100)
while True:
collect_metrics()
time.sleep(15)Custom Collector
PYTHON
from prometheus_client.core import GaugeMetricFamily
class DatabaseCollector:
def collect(self):
conn = psycopg2.connect(self.dsn)
cur = conn.cursor()
size_metric = GaugeMetricFamily(
'postgres_table_size_bytes',
'Table size in bytes',
labels=['schema', 'table']
)
cur.execute("SELECT schemaname, tablename, pg_total_relation_size(schemaname||'.'||tablename) FROM pg_tables")
for row in cur.fetchall():
size_metric.add_metric([row[0], row[1]], row[2])
yield size_metricپیکربندی Prometheus
YAML
scrape_configs:
- job_name: 'custom-myapp'
scrape_interval: 15s
static_configs:
- targets: ['custom-exporter:9100']
labels:
environment: productionنوشتن exporter های سفارشی هر سیستمی که API یا دیتابیس دارد را به یک شهروند درجه اول Prometheus تبدیل میکند.
