Skip to content

Instantly share code, notes, and snippets.

@enes-oerdek
Created August 29, 2023 11:04
Show Gist options
  • Save enes-oerdek/f8770460aa817732ce79752e2fc5dc98 to your computer and use it in GitHub Desktop.
Save enes-oerdek/f8770460aa817732ce79752e2fc5dc98 to your computer and use it in GitHub Desktop.
This is a minimal and simple PHP class for collecting prometheus application metrics and storing them in APC used on Proxer.Me
<?php
class Prometheus
{
private static $prefixCounter = 'php_app_counter_';
private static $prefixGauge = 'php_app_gauge_';
public static function incrementCounter($name)
{
self::increment(self::$prefixCounter, $name);
}
public static function setGauge($name, $value)
{
self::store(self::$prefixGauge, $name, $value);
}
private static function increment($prefix, $name)
{
if (!function_exists('apcu_fetch')) {
die("APCu extension is not installed or enabled.");
}
$key = $prefix . $name;
$currentValue = apcu_fetch($key);
if ($currentValue === false) {
$currentValue = 0;
}
$newValue = $currentValue + 1;
apcu_store($key, $newValue);
}
private static function store($prefix, $name, $value)
{
if (!function_exists('apcu_store')) {
die("APCu extension is not installed or enabled.");
}
$key = $prefix . $name;
apcu_store($key, $value);
}
public static function exposeMetrics()
{
$counterValues = self::fetchMetrics(self::$prefixCounter, 'counter');
$gaugeValues = self::fetchMetrics(self::$prefixGauge, 'gauge');
header('Content-Type: text/plain; version=0.0.4');
foreach ($counterValues as $counterName => $counterValue) {
echo "# HELP {$counterName} The total number of hits for {$counterName}\n";
echo "# TYPE {$counterName} counter\n";
echo "{$counterName} $counterValue\n";
}
foreach ($gaugeValues as $gaugeName => $gaugeValue) {
echo "# HELP {$gaugeName} The gauge value for {$gaugeName}\n";
echo "# TYPE {$gaugeName} gauge\n";
echo "{$gaugeName} $gaugeValue\n";
}
}
private static function fetchMetrics($prefix, $type)
{
$metricValues = [];
foreach (apcu_cache_info()["cache_list"] as $entry) {
if (strpos($entry['info'], $prefix) === 0) {
$metricName = substr($entry['info'], strlen($prefix));
$metricValue = apcu_fetch($entry['info']);
$metricValues[$metricName] = $metricValue === false ? 0 : $metricValue;
}
}
return $metricValues;
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment