Skip to content

Commit f608ea4

Browse files
committed
Merge pull request prometheus#23 from brian-brazil/serverthread
Make it simpler to start a http server. Update docs.
2 parents ef30c5f + 3f44a1c commit f608ea4

File tree

2 files changed

+72
-22
lines changed

2 files changed

+72
-22
lines changed

README.md

Lines changed: 56 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,57 @@
11
# Prometheus Python Client
22

3-
This client is under active development.
3+
The official Python 2 and 3 client for [Prometheus](http://prometheus.io).
4+
5+
## Three Step Demo
6+
7+
**One**: Install the client:
8+
```
9+
pip install prometheus_client
10+
```
11+
12+
**Two**: Paste the following into a Python interpreter:
13+
```python
14+
from prometheus_client import start_http_server,Summary
15+
import random
16+
import time
17+
18+
# Create a metric to track time spent and requests made.
19+
REQUEST_TIME = Summary('request_processing_seconds', 'Time spent processing request')
20+
21+
# Decorate function with metric.
22+
@REQUEST_TIME.time()
23+
def process_request(t):
24+
"""A dummy function that takes some time."""
25+
time.sleep(t)
26+
27+
if __name__ == '__main__':
28+
# Start up the server to expose the metrics.
29+
start_http_server(8000)
30+
# Generate some requests.
31+
while True:
32+
process_request(random.random())
33+
```
34+
35+
**Three**: Visit [http://localhost:8000/](http://localhost:8000/) to view the metrics.
36+
37+
From one easy to use decorator you get:
38+
* `request_processing_seconds_count`: Number of times this function was called.
39+
* `request_processing_seconds_sum`: Total amount of time spent in this function.
40+
41+
Prometheus's `rate` function allows calculation of both requests per second,
42+
and latency over time from this data.
43+
44+
In addition if you're on Linux the `process` metrics expose CPU, memory and
45+
other information about the process for free!
446

547
## Installation
648

749
```
850
pip install prometheus_client
951
```
1052

11-
This package can be found on [PyPI](https://pypi.python.org/pypi/prometheus_client).
53+
This package can be found on
54+
[PyPI](https://pypi.python.org/pypi/prometheus_client).
1255

1356
## Instrumenting
1457

@@ -48,7 +91,6 @@ with c.count_exceptions(ValueError):
4891

4992
Gauges can go up and down.
5093

51-
5294
```python
5395
from prometheus_client import Gauge
5496
g = Gauge('my_inprogress_requests', 'Description of gauge')
@@ -136,7 +178,7 @@ c.labels('post', '/submit').inc()
136178
### Process Collector
137179

138180
The Python Client automatically exports metrics about process CPU usage, RAM,
139-
file descriptors and start time. These all have the prefix `process_`, and
181+
file descriptors and start time. These all have the prefix `process`, and
140182
are only currently available on Linux.
141183

142184
The namespace and pid constructor arguments allows for exporting metrics about
@@ -149,32 +191,24 @@ ProcessCollector(namespace='mydaemon', pid=lambda: open('/var/run/daemon.pid').r
149191

150192
There are several options for exporting metrics.
151193

152-
## HTTP handler
194+
## HTTP
153195

154-
Metrics are usually exposed over HTTP, to be read by the Prometheus server. For example:
196+
Metrics are usually exposed over HTTP, to be read by the Prometheus server.
155197

156-
Python 2:
198+
The easiest way to do this is via `start_http_server`, which will start a HTTP
199+
server in a daemon thread on the given port:
157200

158201
```python
159-
from prometheus_client import MetricsHandler
160-
from BaseHTTPServer import HTTPServer
161-
server_address = ('', 8000)
162-
httpd = HTTPServer(server_address, MetricsHandler)
163-
httpd.serve_forever()
164-
```
165-
166-
Python 3:
167-
168-
```python
169-
from prometheus_client import MetricsHandler
170-
from http.server import HTTPServer
171-
server_address = ('', 8000)
172-
httpd = HTTPServer(server_address, MetricsHandler)
173-
httpd.serve_forever()
202+
from prometheus_client import start_http_server
203+
start_http_server(8000)
174204
```
175205

176206
Visit [http://localhost:8000/](http://localhost:8000/) to view the metrics.
177207

208+
To add Prometheus exposition to an existing HTTP server, see the `MetricsServlet` class
209+
which provides a `BaseHTTPRequestHandler`. It also serves as a simple example of how
210+
to write a custom endpoint.
211+
178212
## Node exporter textfile collector
179213

180214
The [textfile collector](https://github.com/prometheus/node_exporter#textfile-collector)

prometheus_client/__init__.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,10 +10,12 @@
1010
import threading
1111
try:
1212
from BaseHTTPServer import BaseHTTPRequestHandler
13+
from BaseHTTPServer import HTTPServer
1314
except ImportError:
1415
# Python 3
1516
unicode = str
1617
from http.server import BaseHTTPRequestHandler
18+
from http.server import HTTPServer
1719
from functools import wraps
1820
from threading import Lock
1921

@@ -437,6 +439,20 @@ def do_GET(self):
437439
self.end_headers()
438440
self.wfile.write(generate_latest(REGISTRY))
439441

442+
def log_message(self, format, *args):
443+
return
444+
445+
446+
def start_http_server(port, addr=''):
447+
"""Starts a HTTP server for prometheus metrics as a daemon thread."""
448+
class PrometheusMetricsServer(threading.Thread):
449+
def run(self):
450+
httpd = HTTPServer((addr, port), MetricsHandler)
451+
httpd.serve_forever()
452+
t = PrometheusMetricsServer()
453+
t.daemon = True
454+
t.start()
455+
440456

441457
def write_to_textfile(path, registry):
442458
'''Write metrics to the given path.

0 commit comments

Comments
 (0)