Skip to content

Commit daa1626

Browse files
authored
docs: add API reference for all metric types (#1159)
* docs: add API reference for all metric types Adds constructor parameter tables, method documentation, and runnable real-world examples for Counter, Gauge, Histogram, Summary, Info, and Enum. The _index.md quick-pick table now covers all six types. Also fixes labels.md which was missing remove(), remove_by_labels(), and clear() -- the metric pages were already linking to it for those methods. Closes #1021 Signed-off-by: k1chik <[email protected]> * docs: address review feedback on counter example and table header Revert quick-start counter example to use 'my_failures' (no _total suffix) since the library appends it automatically. Rename 'Value goes' column to 'Behavior' in the metric type overview table for clarity across all six types. Signed-off-by: k1chik <[email protected]> * docs: rename table column to 'Update model' Signed-off-by: k1chik <[email protected]> --------- Signed-off-by: k1chik <[email protected]>
1 parent 8673912 commit daa1626

File tree

8 files changed

+638
-42
lines changed

8 files changed

+638
-42
lines changed

docs/content/instrumenting/_index.md

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,10 +3,20 @@ title: Instrumenting
33
weight: 2
44
---
55

6-
Four types of metric are offered: Counter, Gauge, Summary and Histogram.
7-
See the documentation on [metric types](http://prometheus.io/docs/concepts/metric_types/)
6+
Six metric types are available. Pick based on what your value does:
7+
8+
| Type | Update model | Use for |
9+
|------|-----------|---------|
10+
| [Counter](counter/) | only up | requests served, errors, bytes sent |
11+
| [Gauge](gauge/) | up and down | queue depth, active connections, memory usage |
12+
| [Histogram](histogram/) | observations in buckets | request latency, request size — when you need quantiles in queries |
13+
| [Summary](summary/) | observations (count + sum) | request latency, request size — when average is enough |
14+
| [Info](info/) | static key-value pairs | build version, environment metadata |
15+
| [Enum](enum/) | one of N states | task state, lifecycle phase |
16+
17+
See the Prometheus documentation on [metric types](https://prometheus.io/docs/concepts/metric_types/)
818
and [instrumentation best practices](https://prometheus.io/docs/practices/instrumentation/#counter-vs-gauge-summary-vs-histogram)
9-
on how to use them.
19+
for deeper guidance on choosing between Histogram and Summary.
1020

1121
## Disabling `_created` metrics
1222

docs/content/instrumenting/counter.md

Lines changed: 102 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,10 @@ title: Counter
33
weight: 1
44
---
55

6-
Counters go up, and reset when the process restarts.
6+
A Counter tracks a value that only ever goes up. Use it for things you count — requests
7+
served, errors raised, bytes sent. When the process restarts, the counter resets to zero.
78

9+
If your value can go down, use a [Gauge](../gauge/) instead.
810

911
```python
1012
from prometheus_client import Counter
@@ -18,17 +20,110 @@ exposing the time series for counter, a `_total` suffix will be added. This is
1820
for compatibility between OpenMetrics and the Prometheus text format, as OpenMetrics
1921
requires the `_total` suffix.
2022

21-
There are utilities to count exceptions raised:
23+
## Constructor
24+
25+
```python
26+
Counter(name, documentation, labelnames=(), namespace='', subsystem='', unit='', registry=REGISTRY)
27+
```
28+
29+
| Parameter | Type | Default | Description |
30+
|-----------|------|---------|-------------|
31+
| `name` | `str` | required | Metric name. A `_total` suffix is appended automatically when exposing the time series. |
32+
| `documentation` | `str` | required | Help text shown in the `/metrics` output and Prometheus UI. |
33+
| `labelnames` | `Iterable[str]` | `()` | Names of labels for this metric. See [Labels](../labels/). |
34+
| `namespace` | `str` | `''` | Optional prefix. |
35+
| `subsystem` | `str` | `''` | Optional middle component. |
36+
| `unit` | `str` | `''` | Optional unit suffix appended to the metric name. |
37+
| `registry` | `CollectorRegistry` | `REGISTRY` | Registry to register with. Pass `None` to skip registration, which is useful in tests where you create metrics without wanting them in the global registry. |
38+
39+
`namespace`, `subsystem`, and `name` are joined with underscores to form the full metric name:
40+
41+
```python
42+
# namespace='myapp', subsystem='http', name='requests_total'
43+
# produces: myapp_http_requests_total
44+
Counter('requests_total', 'Total requests', namespace='myapp', subsystem='http')
45+
```
46+
47+
## Methods
48+
49+
### `inc(amount=1, exemplar=None)`
50+
51+
Increment the counter by the given amount. The amount must be non-negative.
52+
53+
```python
54+
c.inc() # increment by 1
55+
c.inc(5) # increment by 5
56+
c.inc(0.7) # fractional increments are allowed
57+
```
58+
59+
To attach trace context to an observation, pass an `exemplar` dict. Exemplars are
60+
only rendered in OpenMetrics format. See [Exemplars](../exemplars/) for details.
61+
62+
```python
63+
c.inc(exemplar={'trace_id': 'abc123'})
64+
```
65+
66+
### `reset()`
67+
68+
Reset the counter to zero. Use this when a logical process restarts without
69+
restarting the actual Python process.
70+
71+
```python
72+
c.reset()
73+
```
74+
75+
### `count_exceptions(exception=Exception)`
76+
77+
Count exceptions raised in a block of code or function. Can be used as a
78+
decorator or context manager. Increments the counter each time an exception
79+
of the given type is raised.
2280

2381
```python
2482
@c.count_exceptions()
2583
def f():
26-
pass
84+
pass
2785

2886
with c.count_exceptions():
29-
pass
87+
pass
3088

31-
# Count only one type of exception
89+
# Count only a specific exception type
3290
with c.count_exceptions(ValueError):
33-
pass
34-
```
91+
pass
92+
```
93+
94+
## Labels
95+
96+
See [Labels](../labels/) for how to use `.labels()`, `.remove()`, `.remove_by_labels()`, and `.clear()`.
97+
98+
## Real-world example
99+
100+
Tracking HTTP requests by method and status code in a web application:
101+
102+
```python
103+
from prometheus_client import Counter, start_http_server
104+
105+
REQUESTS = Counter(
106+
'requests_total',
107+
'Total HTTP requests received',
108+
labelnames=['method', 'status'],
109+
namespace='myapp',
110+
)
111+
EXCEPTIONS = Counter(
112+
'exceptions_total',
113+
'Total unhandled exceptions',
114+
labelnames=['handler'],
115+
namespace='myapp',
116+
)
117+
118+
def handle_request(method, handler):
119+
with EXCEPTIONS.labels(handler=handler).count_exceptions():
120+
# ... process the request ...
121+
status = '200'
122+
REQUESTS.labels(method=method, status=status).inc()
123+
124+
if __name__ == '__main__':
125+
start_http_server(8000) # exposes metrics at http://localhost:8000/metrics
126+
# ... start your application ...
127+
```
128+
129+
This produces time series like `myapp_requests_total{method="GET",status="200"}`.

docs/content/instrumenting/enum.md

Lines changed: 86 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3,11 +3,95 @@ title: Enum
33
weight: 6
44
---
55

6-
Enum tracks which of a set of states something is currently in.
6+
Enum tracks which of a fixed set of states something is currently in. Only one state is active at a time. Use it for things like task state machines or lifecycle phases.
77

88
```python
99
from prometheus_client import Enum
1010
e = Enum('my_task_state', 'Description of enum',
1111
states=['starting', 'running', 'stopped'])
1212
e.state('running')
13-
```
13+
```
14+
15+
Enum exposes one time series per state:
16+
- `<name>{<name>="<state>"}` — 1 if this is the current state, 0 otherwise
17+
18+
The first listed state is the default.
19+
20+
Note: Enum metrics do not work in multiprocess mode.
21+
22+
## Constructor
23+
24+
```python
25+
Enum(name, documentation, labelnames=(), namespace='', subsystem='', unit='', registry=REGISTRY, states=[])
26+
```
27+
28+
| Parameter | Type | Default | Description |
29+
|-----------|------|---------|-------------|
30+
| `name` | `str` | required | Metric name. |
31+
| `documentation` | `str` | required | Help text shown in the `/metrics` output and Prometheus UI. |
32+
| `labelnames` | `Iterable[str]` | `()` | Names of labels for this metric. See [Labels](../labels/). The metric name itself cannot be used as a label name. |
33+
| `namespace` | `str` | `''` | Optional prefix. |
34+
| `subsystem` | `str` | `''` | Optional middle component. |
35+
| `unit` | `str` | `''` | Not supported — raises `ValueError`. Enum metrics cannot have a unit. |
36+
| `registry` | `CollectorRegistry` | `REGISTRY` | Registry to register with. Pass `None` to skip registration, which is useful in tests where you create metrics without wanting them in the global registry. |
37+
| `states` | `List[str]` | required | The complete list of valid states. Must be non-empty. The first entry is the initial state. |
38+
39+
`namespace`, `subsystem`, and `name` are joined with underscores to form the full metric name:
40+
41+
```python
42+
# namespace='myapp', subsystem='worker', name='state'
43+
# produces: myapp_worker_state
44+
Enum('state', 'Worker state', states=['idle', 'running', 'error'], namespace='myapp', subsystem='worker')
45+
```
46+
47+
## Methods
48+
49+
### `state(state)`
50+
51+
Set the current state. The value must be one of the strings passed in the `states` list. Raises `ValueError` if the state is not recognized.
52+
53+
```python
54+
e.state('running')
55+
e.state('stopped')
56+
```
57+
58+
## Labels
59+
60+
See [Labels](../labels/) for how to use `.labels()`, `.remove()`, `.remove_by_labels()`, and `.clear()`.
61+
62+
## Real-world example
63+
64+
Tracking the lifecycle state of a background worker:
65+
66+
```python
67+
from prometheus_client import Enum, start_http_server
68+
69+
WORKER_STATE = Enum(
70+
'worker_state',
71+
'Current state of the background worker',
72+
states=['idle', 'running', 'error'],
73+
namespace='myapp',
74+
)
75+
76+
def process_job():
77+
WORKER_STATE.state('running')
78+
try:
79+
# ... do work ...
80+
pass
81+
except Exception:
82+
WORKER_STATE.state('error')
83+
raise
84+
finally:
85+
WORKER_STATE.state('idle')
86+
87+
if __name__ == '__main__':
88+
start_http_server(8000) # exposes metrics at http://localhost:8000/metrics
89+
# ... start your application ...
90+
```
91+
92+
This produces:
93+
```
94+
myapp_worker_state{myapp_worker_state="idle"} 0.0
95+
myapp_worker_state{myapp_worker_state="running"} 1.0
96+
myapp_worker_state{myapp_worker_state="error"} 0.0
97+
```

0 commit comments

Comments
 (0)