Skip to content

Commit b5160d4

Browse files
committed
test w/ custom labels
1 parent 80bc4e4 commit b5160d4

File tree

3 files changed

+35
-14
lines changed

3 files changed

+35
-14
lines changed

README.md

Lines changed: 11 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -204,6 +204,16 @@ that will export the metrics (replace myapp by your project name).
204204

205205
Then we inject the wrapper in settings:
206206

207-
```python
207+
```python
208208
ROOT_URLCONF = "graphite.urls_prometheus_wrapper"
209209
```
210+
211+
## Adding custom labels to middleware (request/response) metrics
212+
213+
You can add application specific labels to metrics reported by the django-prometheus middleware.
214+
This involves extending the classes defined in middleware.py.
215+
216+
* Extend the Metrics class and override the `register_metric` method to add the application specific labels.
217+
* Extend middleware classes, set the metrics_cls class attribute to the the extended metric class and override the label_metric method to attach custom metrics.
218+
219+
See implementation example in [the test app](django_prometheus/tests/end2end/testapp/test_middleware_custom_labels.py#L19-L46)

django_prometheus/middleware.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,7 @@
2525
)
2626

2727

28-
class Metrics:
28+
class Metrics(object):
2929
_instance = None
3030

3131
@classmethod

django_prometheus/tests/end2end/testapp/test_middleware_custom_labels.py

Lines changed: 23 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,6 @@
1+
from prometheus_client import REGISTRY
2+
from prometheus_client.metrics import MetricWrapperBase
3+
14
from django.test import SimpleTestCase, override_settings
25
from django_prometheus.middleware import (
36
Metrics,
@@ -9,8 +12,8 @@
912
from testapp.test_middleware import M, T
1013

1114
EXTENDED_METRICS = [
12-
"django_http_requests_latency_seconds_by_view_method",
13-
"django_http_responses_total_by_status_view_method",
15+
M("requests_latency_seconds_by_view_method"),
16+
M("responses_total_by_status_view_method"),
1417
]
1518

1619

@@ -19,7 +22,7 @@ def register_metric(
1922
self, metric_cls, name, documentation, labelnames=tuple(), **kwargs
2023
):
2124
if name in EXTENDED_METRICS:
22-
labelnames = labelnames + ("view_type", "user_agent_type")
25+
labelnames.extend(("view_type", "user_agent_type"))
2326
return super(CustomMetrics, self).register_metric(
2427
metric_cls, name, documentation, labelnames=labelnames, **kwargs
2528
)
@@ -33,26 +36,30 @@ class AppMetricsAfterMiddleware(PrometheusAfterMiddleware):
3336
metrics_cls = CustomMetrics
3437

3538
def label_metric(self, metric, request, response=None, **labels):
39+
new_labels = labels
3640
if metric._name in EXTENDED_METRICS:
37-
labels.update({"view_type": "foo", "user_agent_type": "browser"})
41+
new_labels = {"view_type": "foo", "user_agent_type": "browser"}
42+
new_labels.update(labels)
3843
return super(AppMetricsAfterMiddleware, self).label_metric(
39-
metric, request, response=response, **labels
44+
metric, request, response=response, **new_labels
4045
)
4146

4247

4348
@override_settings(
44-
MIDDLEWARE_X=get_middleware(
49+
MIDDLEWARE=get_middleware(
4550
"testapp.test_middleware_custom_labels.AppMetricsBeforeMiddleware",
4651
"testapp.test_middleware_custom_labels.AppMetricsAfterMiddleware",
4752
)
4853
)
4954
class TestMiddlewareMetricsWithCustomLabels(PrometheusTestCaseMixin, SimpleTestCase):
50-
"""Test django_prometheus.middleware.
51-
52-
Note that counters related to exceptions can't be tested as
53-
Django's test Client only simulates requests and the exception
54-
handling flow is very different in that simulation.
55-
"""
55+
@classmethod
56+
def setUpClass(cls):
57+
super(TestMiddlewareMetricsWithCustomLabels, cls).setUpClass()
58+
# Allow CustomMetrics to be used
59+
for metric in Metrics._instance.__dict__.values():
60+
if isinstance(metric, MetricWrapperBase):
61+
REGISTRY.unregister(metric)
62+
Metrics._instance = None
5663

5764
def test_request_counters(self):
5865
registry = self.saveRegistry()
@@ -99,6 +106,8 @@ def test_request_counters(self):
99106
status="200",
100107
view="testapp.views.index",
101108
method="GET",
109+
view_type="foo",
110+
user_agent_type="browser",
102111
)
103112
self.assertMetricDiff(
104113
registry,
@@ -107,4 +116,6 @@ def test_request_counters(self):
107116
status="200",
108117
view="testapp.views.help",
109118
method="GET",
119+
view_type="foo",
120+
user_agent_type="browser",
110121
)

0 commit comments

Comments
 (0)