Skip to content

Commit

Permalink
Add time to Measurement
Browse files Browse the repository at this point in the history
  • Loading branch information
fcollonval committed Aug 11, 2024
1 parent ceba9f1 commit d699f8d
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 31 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
# pylint: disable=too-many-ancestors, unused-import

from logging import getLogger
from time import time_ns
from typing import Dict, Generator, Iterable, List, Optional, Union

# This kind of import is needed to avoid Sphinx errors.
Expand All @@ -36,9 +37,7 @@
_logger = getLogger(__name__)


_ERROR_MESSAGE = (
"Expected ASCII string of maximum length 63 characters but got {}"
)
_ERROR_MESSAGE = "Expected ASCII string of maximum length 63 characters but got {}"


class _Synchronous:
Expand Down Expand Up @@ -108,11 +107,8 @@ def __init__(
self._callbacks: List[CallbackT] = []

if callbacks is not None:

for callback in callbacks:

if isinstance(callback, Generator):

# advance generator to it's first yield
next(callback)

Expand All @@ -129,21 +125,18 @@ def inner(
else:
self._callbacks.append(callback)

def callback(
self, callback_options: CallbackOptions
) -> Iterable[Measurement]:
def callback(self, callback_options: CallbackOptions) -> Iterable[Measurement]:
for callback in self._callbacks:
try:
for api_measurement in callback(callback_options):
yield Measurement(
api_measurement.value,
time_unix_nano=time_ns(),
instrument=self,
attributes=api_measurement.attributes,
)
except Exception: # pylint: disable=broad-exception-caught
_logger.exception(
"Callback failed for instrument %s.", self.name
)
_logger.exception("Callback failed for instrument %s.", self.name)


class Counter(_Synchronous, APICounter):
Expand All @@ -152,16 +145,13 @@ def __new__(cls, *args, **kwargs):
raise TypeError("Counter must be instantiated via a meter.")
return super().__new__(cls)

def add(
self, amount: Union[int, float], attributes: Dict[str, str] = None
):
def add(self, amount: Union[int, float], attributes: Dict[str, str] = None):
if amount < 0:
_logger.warning(
"Add amount must be non-negative on Counter %s.", self.name
)
_logger.warning("Add amount must be non-negative on Counter %s.", self.name)
return
time_unix_nano = time_ns()
self._measurement_consumer.consume_measurement(
Measurement(amount, self, attributes)
Measurement(amount, time_unix_nano, self, attributes)
)


Expand All @@ -174,26 +164,23 @@ def __new__(cls, *args, **kwargs):
def add(
self, amount: Union[int, float], attributes: Dict[str, str] = None
):
time_unix_nano = time_ns()
self._measurement_consumer.consume_measurement(
Measurement(amount, self, attributes)
Measurement(amount, time_unix_nano, self, attributes)
)


class ObservableCounter(_Asynchronous, APIObservableCounter):
def __new__(cls, *args, **kwargs):
if cls is ObservableCounter:
raise TypeError(
"ObservableCounter must be instantiated via a meter."
)
raise TypeError("ObservableCounter must be instantiated via a meter.")
return super().__new__(cls)


class ObservableUpDownCounter(_Asynchronous, APIObservableUpDownCounter):
def __new__(cls, *args, **kwargs):
if cls is ObservableUpDownCounter:
raise TypeError(
"ObservableUpDownCounter must be instantiated via a meter."
)
raise TypeError("ObservableUpDownCounter must be instantiated via a meter.")
return super().__new__(cls)


Expand All @@ -203,17 +190,16 @@ def __new__(cls, *args, **kwargs):
raise TypeError("Histogram must be instantiated via a meter.")
return super().__new__(cls)

def record(
self, amount: Union[int, float], attributes: Dict[str, str] = None
):
def record(self, amount: Union[int, float], attributes: Dict[str, str] = None):
if amount < 0:
_logger.warning(
"Record amount must be non-negative on Histogram %s.",
self.name,
)
return
time_unix_nano = time_ns()
self._measurement_consumer.consume_measurement(
Measurement(amount, self, attributes)
Measurement(amount, time_unix_nano, self, attributes)
)


Expand All @@ -226,8 +212,9 @@ def __new__(cls, *args, **kwargs):
def set(
self, amount: Union[int, float], attributes: Dict[str, str] = None
):
time_unix_nano = time_ns()
self._measurement_consumer.consume_measurement(
Measurement(amount, self, attributes)
Measurement(amount, time_unix_nano, self, attributes)
)


Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
from dataclasses import dataclass
from typing import Union

from opentelemetry.context import Context
from opentelemetry.metrics import Instrument
from opentelemetry.util.types import Attributes

Expand All @@ -23,8 +24,17 @@
class Measurement:
"""
Represents a data point reported via the metrics API to the SDK.
Attributes:
value: Measured value
time_unix_nano: The time the API call was made to record the Measurement
instrument: Measurement instrument
context: The active Context of the Measurement at API call time.
attributes: Measurement attributes
"""

value: Union[int, float]
time_unix_nano: int
instrument: Instrument
context: Context
attributes: Attributes = None

0 comments on commit d699f8d

Please sign in to comment.