c3lf-system-3/core/core/metrics.py
lagertonne c3395093c7
Some checks failed
/ test (push) Has been cancelled
/ test (pull_request) Successful in 2m36s
metrics: Make metrics actually usable
2024-12-23 11:30:02 +01:00

36 lines
No EOL
1.2 KiB
Python

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
import logging
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())