PHP code example of imiphp / imi-prometheus

1. Go to this page and download the library: Download imiphp/imi-prometheus library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

imiphp / imi-prometheus example snippets


[
    'MeterRegistry' => [
        'driver'  => \Imi\Prometheus\PrometheusMeterRegistry::class,
        'options' => [
            'adapter' => [
                'class'   => \Imi\Prometheus\Storage\Redis::class,
                'options' => [
                    // 'poolName' => null, // 连接池名称,如果为 null 则使用默认 Redis 连接池
                    // 'prefix' => 'PROMETHEUS_', // 键名前缀
                ],
            ],
            // 所有标签如设为空字符串或 null 则忽略该标签
            'resultTag' => 'result', // 标签名-结果
            'exceptionTag' => 'exception', // 标签名-异常类名
            'instanceTag' => 'instance', // 标签名-实例
            'workerTag' => 'worker', // 标签名-WorkerId
            'instance' => 'imi', // 当前实例名称,每个实例要设置不同
        ],
    ],
]

// 连接池监控
'PoolMonitor' => [
    'enable'         => true, // 启用
    // 'pools'       => null, // 监控的连接池名称数组。如果为 null 则代表监控所有连接池
    // 'interval'    => 10, // 上报时间间隔,单位:秒
    // 'countKey'    => 'pool_count', // 连接总数量键名
    // 'usedKey'     => 'pool_used', // 忙碌连接数量键名
    // 'freeKey'     => 'pool_free', // 空间连接数量键名
    // 'workerIdTag' => 'worker_id', // 工作进程 ID 标签名
    // 'poolNameTag' => 'pool_name', // 连接池标签名
],

// Swoole 服务器指标监控
'SwooleServerMonitor' => [
    'enable'         => true, // 启用
    // 要监控的指标名称数组
    // 详见:https://wiki.swoole.com/#/server/methods?id=stats
    // 格式1:stats() 指标名称 => 实际指标名称
    // 格式2:stats() 指标名称同时作为实际指标名称
    'stats'          => [
        'connection_num' => 'swoole_connection',
        'request_count'  => 'swoole_request_count',
        'coroutine_num'  => 'swoole_coroutine_num',
        'coroutine_num',
    ],
    // 'interval'    => 10, // 上报时间间隔,单位:秒
    // 'workerIdTag' => 'worker_id', // 工作进程 ID 标签名
],

[
    'histogram' => true, // 设置为柱状图,否则默认为 Summary
    'buckets' => [], // 桶,仅柱状图
    'maxAgeSeconds' => 600, // Summary 最大生存时间
    'percentile' => [], // Summary 百分位
]

use Imi\Meter\Annotation\Gauged;
use Imi\Meter\Annotation\Histogram;
use Imi\Meter\Annotation\Summary;
use Imi\Meter\Annotation\Timed;
use Imi\Meter\Enum\TimeUnit;

/**
 * @Gauged(name="test_memory_usage", description="memory usage", tags={"workerId"="{returnValue.workerId}"}, value="{returnValue.memory}")
 */
public function recordMemoryUsage(): array
{
    return [
        'workerId' => Worker::getWorkerId(),
        'memory'   => memory_get_usage(),
    ];
}

/**
 * @Timed(name="test_timed", description="memory usage", baseTimeUnit=TimeUnit::MILLI_SECONDS, options={"quantiles"={0.1, 0.5, 0.99}})
 */
public function testTimed(): int
{
    $ms = mt_rand(10, 1000);
    usleep($ms * 1000);

    return $ms;
}

/**
 * @Timed(name="test_timed_histogram", description="memory usage", baseTimeUnit=TimeUnit::MILLI_SECONDS, options={"histogram"=true, "buckets"={50, 100, 300, 600, 800, 1000}})
 */
public function testTimedHistogram(): int
{
    $ms = mt_rand(10, 1000);
    usleep($ms * 1000);

    return $ms;
}

/**
 * @Histogram(name="test_histogram", baseTimeUnit=TimeUnit::MILLI_SECONDS, buckets={50, 100, 300, 600, 800, 1000})
 */
public function testHistogram(): int
{
    return mt_rand(10, 1000);
}

/**
 * @Summary(name="test_summary", baseTimeUnit=TimeUnit::MILLI_SECONDS, percentile={0.1, 0.5, 0.99})
 */
public function testSummary(): int
{
    return mt_rand(10, 1000);
}

use \Imi\Meter\Facade\MeterRegistry;
use \Imi\Meter\Enum\TimeUnit;

$description = '我是描述';
$tags = ['result' => 'success'];

// counter
MeterRegistry::getDriverInstance()->counter('testCounterManual', $tags, $description)->increment();

// gauge
MeterRegistry::getDriverInstance()->gauge('testGaugeManual', $tags, $description)->record(114514);

// timer
$timer = MeterRegistry::getDriverInstance()->timer('testTimedManual', $tags, $description, TimeUnit::MILLI_SECONDS);
$timerSample = $timer->start();
usleep(mt_rand(10, 1000) * 1000);
$timerSample->stop($timer);

// timer Histogram
$timer = MeterRegistry::getDriverInstance()->timer('testTimedHistogramManual', $tags, $description, TimeUnit::MILLI_SECONDS, [
    'histogram' => true,
    'buckets'   => [100, 500, 1500],
]);
$timerSample = $timer->start();
usleep(mt_rand(10, 1000) * 1000); // 你的耗时代码
$timerSample->stop($timer);

// Histogram
$value = 114514;
$buckets = [100, 500, 1500];
MeterRegistry::getDriverInstance()->histogram('testHistogramManual', $tags, $description, $buckets)->record($value);

// Summary
$value = 114514;
$percentile = [0.1, 0.5, 0.99];
MeterRegistry::getDriverInstance()->summary('testHistogramManual', $tags, $description, $percentile)->record($value);