<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
run-as-root / magento2-prometheus-exporter example snippets
namespace YourNamespace\YourModule\Aggregator;
use RunAsRoot\PrometheusExporter\Api\MetricAggregatorInterface;
use RunAsRoot\PrometheusExporter\Service\UpdateMetricService;
class CustomMetricAggregator implements MetricAggregatorInterface
{
private UpdateMetricService $updateMetricService;
public function __construct(UpdateMetricService $updateMetricService)
{
$this->updateMetricService = $updateMetricService;
}
public function aggregate(): void
{
// Your metric collection logic here
$value = $this->calculateCustomMetric();
$this->updateMetricService->update(
'your_custom_metric_total',
(string) $value,
'gauge',
'Description of your custom metric',
['label1' => 'value1', 'label2' => 'value2']
);
}
private function calculateCustomMetric(): int
{
// Implement your metric calculation
return 42;
}
}
namespace YourNamespace\YourModule\Aggregator;
use Magento\Review\Model\ResourceModel\Review\CollectionFactory;
use RunAsRoot\PrometheusExporter\Api\MetricAggregatorInterface;
use RunAsRoot\PrometheusExporter\Service\UpdateMetricService;
class ProductRatingAggregator implements MetricAggregatorInterface
{
private CollectionFactory $reviewCollectionFactory;
private UpdateMetricService $updateMetricService;
public function __construct(
CollectionFactory $reviewCollectionFactory,
UpdateMetricService $updateMetricService
) {
$this->reviewCollectionFactory = $reviewCollectionFactory;
$this->updateMetricService = $updateMetricService;
}
public function aggregate(): void
{
$collection = $this->reviewCollectionFactory->create()
->addStatusFilter(\Magento\Review\Model\Review::STATUS_APPROVED);
$averageRating = $collection->getConnection()
->fetchOne('SELECT AVG(rating_value) FROM rating_option_vote');
$this->updateMetricService->update(
'magento_product_average_rating',
(string) round($averageRating, 2),
'gauge',
'Average product rating across all approved reviews'
);
}
}