46 $this->statsFactory = $statsFactory;
49 throw new InvalidArgumentException(
'Stats: Histogram buckets cannot be an empty array.' );
51 $bucketCount = count( $buckets );
52 if ( $bucketCount > self::MAX_BUCKETS ) {
53 throw new InvalidArgumentException(
54 "Stats: Too many buckets defined. Got:{$bucketCount}, Max:" . self::MAX_BUCKETS
57 foreach ( $buckets as $bucket ) {
58 if ( !( is_float( $bucket ) || is_int( $bucket ) ) ) {
59 throw new InvalidArgumentException(
'Stats: Histogram buckets can only be float or int.' );
62 $normalizedBuckets = array_unique( $buckets );
63 sort( $normalizedBuckets, SORT_NUMERIC );
64 if ( $buckets !== $normalizedBuckets ) {
65 throw new InvalidArgumentException(
66 'Stats: Histogram buckets must be unique and in order of least to greatest.'
69 $this->buckets = $buckets;
88 public function observe(
float $value ): void {
89 $count = $this->statsFactory->getCounter(
"{$this->name}_count" );
90 $bucket = $this->statsFactory->getCounter(
"{$this->name}_bucket" );
91 $sum = $this->statsFactory->getCounter(
"{$this->name}_sum" );
93 foreach ( $this->labels as $k => $v ) {
94 $count->setLabel( $k, $v );
95 $bucket->setLabel( $k, $v );
96 $sum->setLabel( $k, $v );
99 if ( $bucket->getSampleCount() === 0 ) {
100 $this->preloadBuckets( $bucket );
103 $bucket->setBucket(
'+Inf' )->increment();
104 foreach ( $this->buckets as $le ) {
105 if ( $value <= $le ) {
106 $bucket->setBucket( $le )->increment();
111 $sum->incrementBy( $value );