PluginProbe
DecaLog / 4.4.0
DecaLog v4.4.0
3.0.2 3.1.0 3.10.0 3.2.0 3.3.0 3.4.0 3.4.1 3.5.0 3.5.1 3.6.0 3.6.1 3.6.2 3.6.3 3.7.0 3.7.1 3.8.0 3.9.0 3.9.1 4.0.0 4.1.0 4.2.0 4.3.0 4.3.1 4.4.0 4.5.0 All 75 releases
decalog / includes / libraries / prometheus / RenderDatadogFormat.php

RenderDatadogFormat.php in DecaLog 4.4.0, at includes/libraries/prometheus/RenderDatadogFormat.php

101 lines 2.3 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2
3 declare(strict_types=1);
4
5 namespace Prometheus;
6
7 use Decalog\System\Environment;
8 use Decalog\System\Blog;
9
10 class RenderDatadogFormat implements RendererInterface {
11
12 /**
13 * The array of tag names.
14 *
15 * @since 3.0.0
16 * @var array $tagnames The tag names.
17 */
18 private $tagnames = [];
19
20 /**
21 * The array of tag values.
22 *
23 * @since 3.0.0
24 * @var array $tagvalues The tag values.
25 */
26 private $tagvalues = [];
27
28 /**
29 * The hostname.
30 *
31 * @since 3.0.0
32 * @var string $host The hostname.
33 */
34 private $host = '';
35
36 /**
37 * @param MetricFamilySamples[] $metrics
38 * @return string
39 */
40 public function render( array $metrics ): string {
41 $this->host = gethostname();
42 $lines = [];
43 foreach ( $metrics as $metric ) {
44 foreach ( $metric->getSamples() as $sample ) {
45 $lines[] = $this->renderSample( $metric, $sample );
46 }
47 }
48 return '{"series":[' . implode( ',', $lines ) . ']}';
49 }
50
51 /**
52 * @param MetricFamilySamples $metric
53 * @param Sample $sample
54 * @return string
55 */
56 private function renderSample( MetricFamilySamples $metric, Sample $sample ): string {
57 $rmetric = [
58 'host' => $this->host,
59 'type' => $metric->getType(),
60 'metric' => str_replace( '_', '.', $sample->getName() ),
61 'points' => [
62 [
63 (string) time(),
64 (string) $sample->getValue(),
65 ],
66 ],
67 ];
68 $labelNames = $metric->getLabelNames();
69 if ( $metric->hasLabelNames() || $sample->hasLabelNames() ) {
70 $rmetric['tags'] = $this->escapeAllLabels( $labelNames, $sample );
71 }
72 return wp_json_encode( $rmetric );
73 }
74
75 /**
76 * @param string $v
77 * @return string
78 */
79 private function escapeLabelValue( string $v ): string {
80 return str_replace( [ '\\', "\n", '"', ' ', '=', ',' ], [ '\\\\', "\\n", '\\"', '\\ ', '', '' ], $v );
81 }
82
83 /**
84 * @param string[] $labelNames
85 * @param Sample $sample
86 *
87 * @return string[]
88 */
89 private function escapeAllLabels( array $labelNames, Sample $sample ): array {
90 $escapedLabels = [];
91 $labels = array_combine( array_merge( $labelNames, $sample->getLabelNames(), $this->tagnames ), array_merge( $sample->getLabelValues(), $this->tagvalues ) );
92 if ( $labels === false ) {
93 return [];
94 }
95 foreach ( $labels as $labelName => $labelValue ) {
96 $escapedLabels[] = $labelName . ':' . $this->escapeLabelValue( (string) $labelValue );
97 }
98 return $escapedLabels;
99 }
100 }
101