The official Python 2 and 3 client for Prometheus.
One: Install the client:
pip install prometheus_client
Two: Paste the following into a Python interpreter:
from prometheus_client import start_http_server, Summary
import random
import time
# Create a metric to track time spent and requests made.
REQUEST_TIME = Summary('request_processing_seconds', 'Time spent processing request')
# Decorate function with metric.
@REQUEST_TIME.time()
def process_request(t):
"""A dummy function that takes some time."""
time.sleep(t)
if __name__ == '__main__':
# Start up the server to expose the metrics.
start_http_server(8000)
# Generate some requests.
while True:
process_request(random.random())
Three: Visit http://localhost:8000/ to view the metrics.
From one easy to use decorator you get:
request_processing_seconds_count
: Number of times this function was called.request_processing_seconds_sum
: Total amount of time spent in this function.
Prometheus's rate
function allows calculation of both requests per second,
and latency over time from this data.
In addition if you're on Linux the process
metrics expose CPU, memory and
other information about the process for free!
pip install prometheus_client
This package can be found on PyPI.
Four types of metric are offered: Counter, Gauge, Summary and Histogram. See the documentation on metric types and instrumentation best practices on how to use them.
Counters go up, and reset when the process restarts.
from prometheus_client import Counter
c = Counter('my_failures', 'Description of counter')
c.inc() # Increment by 1
c.inc(1.6) # Increment by given value
If there is a suffix of _total
on the metric name, it will be removed. When
exposing the time series for counter, a _total
suffix will be added. This is
for compatibility between OpenMetrics and the Prometheus text format, as OpenMetrics
requires the _total
suffix.
There are utilities to count exceptions raised:
@c.count_exceptions()
def f():
pass
with c.count_exceptions():
pass
# Count only one type of exception
with c.count_exceptions(ValueError):
pass
Gauges can go up and down.
from prometheus_client import Gauge
g = Gauge('my_inprogress_requests', 'Description of gauge')
g.inc() # Increment by 1
g.dec(10) # Decrement by given value
g.set(4.2) # Set to a given value
There are utilities for common use cases:
g.set_to_current_time() # Set to current unixtime
# Increment when entered, decrement when exited.
@g.track_inprogress()
def f():
pass
with g.track_inprogress():
pass
A Gauge can also take its value from a callback:
d = Gauge('data_objects', 'Number of objects')
my_dict = {}
d.set_function(lambda: len(my_dict))
Summaries track the size and number of events.
from prometheus_client import Summary
s = Summary('request_latency_seconds', 'Description of summary')
s.observe(4.7) # Observe 4.7 (seconds in this case)
There are utilities for timing code:
@s.time()
def f():
pass
with s.time():
pass
The Python client doesn't store or expose quantile information at this time.
Histograms track the size and number of events in buckets. This allows for aggregatable calculation of quantiles.
from prometheus_client import Histogram
h = Histogram('request_latency_seconds', 'Description of histogram')
h.observe(4.7) # Observe 4.7 (seconds in this case)
The default buckets are intended to cover a typical web/rpc request from milliseconds to seconds.
They can be overridden by passing buckets
keyword argument to Histogram
.
There are utilities for timing code:
@h.time()
def f():
pass
with h.time():
pass
Info tracks key-value information, usually about a whole target.
from prometheus_client import Info
i = Info('my_build_version', 'Description of info')
i.info({'version': '1.2.3', 'buildhost': 'foo@bar'})
Enum tracks which of a set of states something is currently in.
from prometheus_client import Enum
e = Enum('my_task_state', 'Description of enum',
states=['starting', 'running', 'stopped'])
e.state('running')
All metrics can have labels, allowing grouping of related time series.
See the best practices on naming and labels.
Taking a counter as an example:
from prometheus_client import Counter
c = Counter('my_requests_total', 'HTTP Failures', ['method', 'endpoint'])
c.labels('get', '/').inc()
c.labels('post', '/submit').inc()
Labels can also be passed as keyword-arguments:
from prometheus_client import Counter
c = Counter('my_requests_total', 'HTTP Failures', ['method', 'endpoint'])
c.labels(method='get', endpoint='/').inc()
c.labels(method='post', endpoint='/submit').inc()
The Python client automatically exports metrics about process CPU usage, RAM,
file descriptors and start time. These all have the prefix process
, and
are only currently available on Linux.
The namespace and pid constructor arguments allows for exporting metrics about other processes, for example:
ProcessCollector(namespace='mydaemon', pid=lambda: open('/var/run/daemon.pid').read())
The client also automatically exports some metadata about Python. If using Jython,
metadata about the JVM in use is also included. This information is available as
labels on the python_info
metric. The value of the metric is 1, since it is the
labels that carry information.
There are several options for exporting metrics.
Metrics are usually exposed over HTTP, to be read by the Prometheus server.
The easiest way to do this is via start_http_server
, which will start a HTTP
server in a daemon thread on the given port:
from prometheus_client import start_http_server
start_http_server(8000)
Visit http://localhost:8000/ to view the metrics.
To add Prometheus exposition to an existing HTTP server, see the MetricsHandler
class
which provides a BaseHTTPRequestHandler
. It also serves as a simple example of how
to write a custom endpoint.
To use prometheus with twisted, there is MetricsResource
which exposes metrics as a twisted resource.
from prometheus_client.twisted import MetricsResource
from twisted.web.server import Site
from twisted.web.resource import Resource
from twisted.internet import reactor
root = Resource()
root.putChild(b'metrics', MetricsResource())
factory = Site(root)
reactor.listenTCP(8000, factory)
reactor.run()
To use Prometheus with WSGI, there is
make_wsgi_app
which creates a WSGI application.
from prometheus_client import make_wsgi_app
from wsgiref.simple_server import make_server
app = make_wsgi_app()
httpd = make_server('', 8000, app)
httpd.serve_forever()
Such an application can be useful when integrating Prometheus metrics with WSGI apps.
The method start_wsgi_server
can be used to serve the metrics through the
WSGI reference implementation in a new thread.
from prometheus_client import start_wsgi_server
start_wsgi_server(8000)
To use Prometheus with Flask we need to serve metrics through a Prometheus WSGI application. This can be achieved using Flask's application dispatching. Below is a working example.
Save the snippet below in a myapp.py
file
from flask import Flask
from werkzeug.wsgi import DispatcherMiddleware
from prometheus_client import make_wsgi_app
# Create my app
app = Flask(__name__)
# Add prometheus wsgi middleware to route /metrics requests
app_dispatch = DispatcherMiddleware(app, {
'/metrics': make_wsgi_app()
})
Run the example web application like this
# Install uwsgi if you do not have it
pip install uwsgi
uwsgi --http 127.0.0.1:8000 --wsgi-file myapp.py --callable app_dispatch
Visit http://localhost:8000/metrics to see the metrics