Compare commits

..

1 commit

Author SHA1 Message Date
c3395093c7 metrics: Make metrics actually usable
Some checks failed
/ test (push) Has been cancelled
/ test (pull_request) Successful in 2m36s
2024-12-23 11:30:02 +01:00

View file

@ -1,16 +1,36 @@
from django.apps import apps from django.apps import apps
from prometheus_client.core import CounterMetricFamily, REGISTRY 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 ModelCountCollector(object): class ItemCountCollector(object):
def collect(self): def collect(self):
counter = CounterMetricFamily('model_count', 'Number of objects per model', labels=['model', 'app']) counter = CounterMetricFamily("item_count", "Current number of items", labels=['event', 'state'])
yield counter
if not apps.models_ready or not apps.apps_ready:
return
for app_name, app_config in apps.app_configs.items():
for model in app_config.get_models():
counter.add_metric([model.__name__, app_name], model.objects.count())
yield counter yield counter
REGISTRY.register(ModelCountCollector()) 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())