Skip to content

Instantly share code, notes, and snippets.

@davideuler
Last active May 13, 2018 00:22
Show Gist options
  • Save davideuler/9889d7928d0feddf5816f2a09ae90834 to your computer and use it in GitHub Desktop.
Save davideuler/9889d7928d0feddf5816f2a09ae90834 to your computer and use it in GitHub Desktop.
A simple Prometheus metrics server in python for statistics of website user count
#!/usr/bin/env python3
# -*- encoding: utf-8 -*-
import time
from pymongo import MongoClient
from prometheus_client import start_http_server
from prometheus_client.core import GaugeMetricFamily, CounterMetricFamily, REGISTRY
from config.settings import MONGO_USER, MONGO_PASS, MONGO_URL, MONGO_DBNAME
'''
It is a prometheus exporter,which export website user count to prometheus.
Prometheus import data by tihs metrics server as a target, and show the user count trending on Grafana.
In the same way, you can visualize user orders trending, revenue trending, etc....
'''
class CustomCollector(object):
def __init__(self):
self.client = MongoClient('mongodb://%s:%s@%s' % (MONGO_USER, MONGO_PASS, MONGO_URL))
self.db = self.client[MONGO_DBNAME]
def collect(self):
users_count = self.db.users.find().count()
c = CounterMetricFamily('website_user_total', 'total users', labels=['count','users_count'])
c.add_metric(['users_count'], users_count)
yield c
if __name__ == '__main__':
port = 8000
print('starting server http://127.0.0.1:{}/metrics'.format(port))
REGISTRY.register(CustomCollector())
# Start up the server to expose the metrics.
start_http_server(port, addr="127.0.0.1")
while True:
time.sleep(3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment