Source code for aidputils.agents.toolkit.metrics_util
"""Utility helpers for creating and recording OpenTelemetry metrics for toolkit components."""
import logging
from opentelemetry import metrics
logger = logging.getLogger(__name__)
[docs]
class MetricUtility:
"""Small wrapper around an OpenTelemetry meter.
This helper keeps toolkit code concise by centralizing the common pattern of:
1. creating a meter for a logical component, and
2. creating and incrementing counters with optional attributes.
Parameters
----------
meter_name:
The OpenTelemetry meter scope name used to group emitted metrics.
"""
def __init__(self, meter_name: str):
"""Initialize the metric utility with a named meter."""
self.meter = metrics.get_meter(meter_name)
[docs]
def create_counter(self, name: str, description: str = ""):
"""Create and return a counter instrument.
Parameters
----------
name:
Metric name exposed to the telemetry backend.
description:
Optional human-readable description for dashboards and observability tools.
"""
return self.meter.create_counter(name, description=description)
[docs]
def increment_counter(self, counter, value: int = 1, attributes: dict | None = None) -> None:
"""Increment a counter safely.
Parameters
----------
counter:
The OpenTelemetry counter returned by :meth:`create_counter`.
value:
Amount to add to the counter.
attributes:
Optional dimension map attached to the metric sample.
Notes
-----
Metric emission should never break the calling workflow. Any telemetry errors are
logged and suppressed.
"""
try:
if attributes:
counter.add(value, attributes=attributes)
else:
counter.add(value)
except Exception:
logger.exception("Could not increment counter")