40 private const RE_VALID_NAME_AND_LABEL_NAME =
'/^[a-zA-Z_][a-zA-Z0-9_]*$/';
76 $this->prefix = $config[
'prefix'];
77 $this->extension = $config[
'extension'];
78 $this->name = $config[
'name'];
79 $this->sampleRate = $config[
'sampleRate'];
80 $this->format = $config[
'format'];
81 if ( !preg_match( self::RE_VALID_NAME_AND_LABEL_NAME, $this->name ) ) {
84 $this->labels = $config[
'labels'];
85 foreach ( $this->labels as $label ) {
86 if ( !preg_match( self::RE_VALID_NAME_AND_LABEL_NAME, $label ) ) {
105 $this->samples[] = $sample;
113 switch ( $this->format ) {
115 foreach ( $this->getFilteredSamples() as $sample ) {
116 $output[] = $this->renderDogStatsD( $sample );
120 foreach ( $this->getFilteredSamples() as $sample ) {
121 $output[] = $this->renderStatsD( $sample );
135 if ( count( $this->labels ) !== count( $labels ) ) {
137 'Not enough or too many labels provided to metric instance.'
138 .
'Configured: ' . json_encode( $this->labels ) .
' Provided: ' . json_encode( $labels )
147 private function getFilteredSamples() {
148 if ( $this->sampleRate === 1.0 ) {
149 return $this->samples;
152 $randMax = mt_getrandmax();
153 foreach ( $this->samples as $sample ) {
154 if ( mt_rand() / $randMax < $this->sampleRate ) {
166 private function renderStatsD( Sample $sample ): string {
167 $stat = implode(
'.',
168 array_merge( [ $this->prefix, $this->extension, $this->name ], $sample->getLabels() )
170 $value =
':' . $sample->getValue();
171 $type =
'|' . $this->typeIndicator;
172 $sampleRate = $this->sampleRate !== 1.0 ?
'|@' . $this->sampleRate :
'';
174 return $stat . $value .
$type . $sampleRate;
184 private function renderDogStatsD( Sample $sample ): string {
185 $stat = implode(
'.', [ $this->prefix, $this->extension, $this->name ] );
186 $sampleLabels = $sample->getLabels();
188 foreach ( $this->labels as $i => $label ) {
189 $labels[] = $label .
':' . $sampleLabels[$i];
191 $value =
':' . $sample->getValue();
192 $type =
'|' . $this->typeIndicator;
193 $sampleRate = $this->sampleRate !== 1.0 ?
'|@' . $this->sampleRate :
'';
194 $tags = $labels === [] ?
'' :
'|#' . implode(
',', $labels );
195 return $stat . $value .
$type . $sampleRate . $tags;