_metrics.py 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. """
  2. NOTE: This file contains experimental code that may be changed or removed at any
  3. time without prior notice.
  4. """
  5. import time
  6. from typing import Any, Optional, TYPE_CHECKING, Union
  7. import sentry_sdk
  8. from sentry_sdk.utils import safe_repr
  9. if TYPE_CHECKING:
  10. from sentry_sdk._types import Metric, MetricType
  11. def _capture_metric(
  12. name, # type: str
  13. metric_type, # type: MetricType
  14. value, # type: float
  15. unit=None, # type: Optional[str]
  16. attributes=None, # type: Optional[dict[str, Any]]
  17. ):
  18. # type: (...) -> None
  19. client = sentry_sdk.get_client()
  20. attrs = {} # type: dict[str, Union[str, bool, float, int]]
  21. if attributes:
  22. for k, v in attributes.items():
  23. attrs[k] = (
  24. v
  25. if (
  26. isinstance(v, str)
  27. or isinstance(v, int)
  28. or isinstance(v, bool)
  29. or isinstance(v, float)
  30. )
  31. else safe_repr(v)
  32. )
  33. metric = {
  34. "timestamp": time.time(),
  35. "trace_id": None,
  36. "span_id": None,
  37. "name": name,
  38. "type": metric_type,
  39. "value": float(value),
  40. "unit": unit,
  41. "attributes": attrs,
  42. } # type: Metric
  43. client._capture_metric(metric)
  44. def count(
  45. name, # type: str
  46. value, # type: float
  47. unit=None, # type: Optional[str]
  48. attributes=None, # type: Optional[dict[str, Any]]
  49. ):
  50. # type: (...) -> None
  51. _capture_metric(name, "counter", value, unit, attributes)
  52. def gauge(
  53. name, # type: str
  54. value, # type: float
  55. unit=None, # type: Optional[str]
  56. attributes=None, # type: Optional[dict[str, Any]]
  57. ):
  58. # type: (...) -> None
  59. _capture_metric(name, "gauge", value, unit, attributes)
  60. def distribution(
  61. name, # type: str
  62. value, # type: float
  63. unit=None, # type: Optional[str]
  64. attributes=None, # type: Optional[dict[str, Any]]
  65. ):
  66. # type: (...) -> None
  67. _capture_metric(name, "distribution", value, unit, attributes)