Skip to content

Commit f3a101e

Browse files
committed
Add db query duration metric
1 parent 74c6d1b commit f3a101e

File tree

3 files changed

+17
-5
lines changed

3 files changed

+17
-5
lines changed

django_prometheus/db/__init__.py

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
errors_total,
77
execute_many_total,
88
execute_total,
9+
query_duration_seconds,
910
)
1011

1112
__all__ = [
@@ -15,4 +16,5 @@
1516
"errors_total",
1617
"execute_many_total",
1718
"execute_total",
19+
"query_duration_seconds",
1820
]

django_prometheus/db/common.py

Lines changed: 7 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
errors_total,
55
execute_many_total,
66
execute_total,
7+
query_duration_seconds,
78
)
89

910

@@ -57,21 +58,23 @@ def ExportingCursorWrapper(cursor_class, alias, vendor):
5758
vendor name.
5859
"""
5960

61+
labels = {"alias": alias, "vendor": vendor}
62+
6063
class CursorWrapper(cursor_class):
6164
"""Extends the base CursorWrapper to count events."""
6265

6366
def execute(self, *args, **kwargs):
6467
execute_total.labels(alias, vendor).inc()
65-
with ExceptionCounterByType(
66-
errors_total, extra_labels={"alias": alias, "vendor": vendor}
68+
with query_duration_seconds.labels(**labels).time(), (
69+
ExceptionCounterByType(errors_total, extra_labels=labels)
6770
):
6871
return super(CursorWrapper, self).execute(*args, **kwargs)
6972

7073
def executemany(self, query, param_list, *args, **kwargs):
7174
execute_total.labels(alias, vendor).inc(len(param_list))
7275
execute_many_total.labels(alias, vendor).inc(len(param_list))
73-
with ExceptionCounterByType(
74-
errors_total, extra_labels={"alias": alias, "vendor": vendor}
76+
with query_duration_seconds.labels(**labels).time(), (
77+
ExceptionCounterByType(errors_total, extra_labels=labels)
7578
):
7679
return super(CursorWrapper, self).executemany(
7780
query, param_list, *args, **kwargs

django_prometheus/db/metrics.py

Lines changed: 8 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
from prometheus_client import Counter
1+
from prometheus_client import Counter, Histogram
22

33
from django_prometheus.conf import NAMESPACE
44

@@ -41,3 +41,10 @@
4141
["alias", "vendor", "type"],
4242
namespace=NAMESPACE,
4343
)
44+
45+
query_duration_seconds = Histogram(
46+
"django_db_query_duration_seconds",
47+
("Histogram of query duration by database and vendor."),
48+
["alias", "vendor"],
49+
namespace=NAMESPACE,
50+
)

0 commit comments

Comments
 (0)