| 1 | <?php |
| 2 | /** |
| 3 | * This program is free software; you can redistribute it and/or modify |
| 4 | * it under the terms of the GNU General Public License as published by |
| 5 | * the Free Software Foundation; either version 2 of the License, or |
| 6 | * (at your option) any later version. |
| 7 | * |
| 8 | * This program is distributed in the hope that it will be useful, |
| 9 | * but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 10 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 11 | * GNU General Public License for more details. |
| 12 | * |
| 13 | * You should have received a copy of the GNU General Public License along |
| 14 | * with this program; if not, write to the Free Software Foundation, Inc., |
| 15 | * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. |
| 16 | * http://www.gnu.org/copyleft/gpl.html |
| 17 | * @file |
| 18 | */ |
| 19 | |
| 20 | declare( strict_types=1 ); |
| 21 | |
| 22 | namespace Wikimedia\Stats\Formatters; |
| 23 | |
| 24 | use Wikimedia\Stats\Metrics\MetricInterface; |
| 25 | |
| 26 | /** |
| 27 | * DogStatsD Wire Format Implementation |
| 28 | * |
| 29 | * @author Cole White |
| 30 | * @since 1.41 |
| 31 | */ |
| 32 | class DogStatsdFormatter implements FormatterInterface { |
| 33 | /** @inheritDoc */ |
| 34 | public function getFormattedSamples( string $prefix, MetricInterface $metric ): array { |
| 35 | $output = []; |
| 36 | |
| 37 | // append component to prefix if set |
| 38 | if ( $metric->getComponent() !== '' ) { |
| 39 | $prefix .= ".{$metric->getComponent()}"; |
| 40 | } |
| 41 | |
| 42 | foreach ( $metric->getSamples() as $sample ) { |
| 43 | // dot-separate prefix, component, and name `prefix.component.name` |
| 44 | $stat = implode( '.', [ $prefix, $metric->getName() ] ); |
| 45 | |
| 46 | // merge value with separator `:42` |
| 47 | $value = ':' . $sample->getValue(); |
| 48 | |
| 49 | // merge type indicator with separator `|c` |
| 50 | $type = '|' . $metric->getTypeIndicator(); |
| 51 | |
| 52 | // blank string if samplerate is 1.0, otherwise add samplerate indicator `|@0.5` |
| 53 | $sampleRate = $metric->getSampleRate() !== 1.0 ? '|@' . $metric->getSampleRate() : ''; |
| 54 | |
| 55 | // merge label keys and label values `key:value` |
| 56 | $labels = []; |
| 57 | $labelValues = $sample->getLabelValues(); |
| 58 | foreach ( $metric->getLabelKeys() as $i => $labelKey ) { |
| 59 | $labels[] = $labelKey . ':' . $labelValues[$i]; |
| 60 | } |
| 61 | |
| 62 | // combine label kv pairs `|# key1:value1,key2:value2` |
| 63 | $tags = $labels === [] ? '' : '|#' . implode( ",", $labels ); |
| 64 | |
| 65 | // combine and append to output `prefix.component.name:42|c|@0.5|#key1:value1,key2:value2` |
| 66 | $output[] = $stat . $value . $type . $sampleRate . $tags; |
| 67 | } |
| 68 | return $output; |
| 69 | } |
| 70 | } |