metrics: Make metrics actually usable #104
2 changed files with 37 additions and 0 deletions
35
core/core/metrics.py
Normal file
35
core/core/metrics.py
Normal file
|
@ -0,0 +1,35 @@
|
||||||
|
from django.apps import apps
|
||||||
|
from prometheus_client.core import CounterMetricFamily, REGISTRY
|
||||||
|
from django.db.models import Case, Value, When, BooleanField, Count
|
||||||
|
from inventory.models import Item
|
||||||
|
|
||||||
|
class ItemCountCollector(object):
|
||||||
|
|
||||||
|
def collect(self):
|
||||||
|
counter = CounterMetricFamily("item_count", "Current number of items", labels=['event', 'state'])
|
||||||
|
|
||||||
|
yield counter
|
||||||
|
|
||||||
|
if not apps.models_ready or not apps.apps_ready:
|
||||||
|
return
|
||||||
|
|
||||||
|
queryset = (
|
||||||
|
Item.all_objects
|
||||||
|
.annotate(
|
||||||
|
returned=Case(
|
||||||
|
When(returned_at__isnull=False, then=Value(False)),
|
||||||
|
default=Value(True),
|
||||||
|
output_field=BooleanField()
|
||||||
|
)
|
||||||
|
)
|
||||||
|
.values('event__slug', 'returned', 'event_id')
|
||||||
|
.annotate(amount=Count('id'))
|
||||||
|
.order_by('event__slug', 'returned') # Optional: order by slug and returned
|
||||||
|
)
|
||||||
|
|
||||||
|
for e in queryset:
|
||||||
|
counter.add_metric([e["event__slug"].lower(), str(e["returned"])], e["amount"])
|
||||||
|
|
||||||
|
yield counter
|
||||||
|
|
||||||
|
REGISTRY.register(ItemCountCollector())
|
|
@ -19,6 +19,8 @@ from django.urls import path, include
|
||||||
|
|
||||||
from .version import get_info
|
from .version import get_info
|
||||||
|
|
||||||
|
from .metrics import *
|
||||||
|
|
||||||
urlpatterns = [
|
urlpatterns = [
|
||||||
path('djangoadmin/', admin.site.urls),
|
path('djangoadmin/', admin.site.urls),
|
||||||
path('api/2/', include('inventory.api_v2')),
|
path('api/2/', include('inventory.api_v2')),
|
||||||
|
|
Loading…
Add table
Reference in a new issue