Compare commits

..

1 commit

Author SHA1 Message Date
2e4629d45e metrics: Make metrics actually usable
All checks were successful
/ test (push) Successful in 2m52s
/ test (pull_request) Successful in 2m38s
2024-12-21 22:14:53 +01:00

View file

@ -1,36 +1,16 @@
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):
class ModelCountCollector(object):
def collect(self):
counter = CounterMetricFamily("item_count", "Current number of items", labels=['event', 'state'])
counter = CounterMetricFamily('model_count', 'Number of objects per model', labels=['model', 'app'])
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"])
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
REGISTRY.register(ItemCountCollector())
REGISTRY.register(ModelCountCollector())