tutu-ru/lib-metrics

3.0.2 2019-08-09 11:14 UTC

README

版本 3.0.* 已废弃 - 使用第二个主版本号!

将指标发送到 statsd_exporter

use TutuRu\Metrics\StatsdExporterClientFactory;

$statsdExporterClient = StatsdExporterClientFactory::create($config, $psrLogger);

$statsdExporterClient->count('counter', 10);
$statsdExporterClient->gauge('gauge', 50);

// в этот момент происходит реальная отправка данных
$statsdExporterClient->save();

指标收集器

一个对象,允许在一个地方封装测量逻辑。

use TutuRu\Metrics\StatsdExporterClientFactory;
use TutuRu\Metrics\MetricCollector;

$statsdExporterClient = StatsdExporterClientFactory::create($config, $psrLogger);

class MyDataCollector extends MetricCollector
{
    protected function getTimersMetricName(): string
    {
        return 'my_metrics';
    }


    protected function getTimersMetricTags(): array
    {
        return ['env' => 'test'];
    }


    protected function onSave(): void
    {
        $this->increment('additional_data');
    }
}

$collector = new MyDataCollector();
$collector->startTiming();
// code
$collector->endTiming();
$collector->sendToStatsdExporter($statsdExporterClient);

$statsdExporterClient->save();

向其他对象传递客户端

为了使客户端声明可以传递 stats_exporter,需要接口 MetricAwareInterface

示例

use TutuRu\Metrics\StatsdExporterClientFactory;
use TutuRu\Metrics\StatsdExporterAwareInterface;
use TutuRu\Metrics\StatsdExporterAwareTrait;

$statsdExporterClient = StatsdExporterClientFactory::create($config, $psrLogger);

class MyObject implements StatsdExporterAwareInterface
{
    use StatsdExporterAwareTrait;

    public function doSomething()
    {
        if (!is_null($this->statsdExporterClient)) {
            $this->statsdExporterClient->summary('summary_metric', 500);
        }
    }
}

$object = new MyObject();
$object->setStatsdExporterClient($statsdExporterClient);
$object->doSomething();

$statsdExporterClient->save();

在其他库中的使用

use PHPUnit\Framework\TestCase;
use TutuRu\Tests\Metrics\MemoryStatsdExporter\MemoryStatsdExporterClient;

class MyTest extends TestCase
{
    public function testMetrics()
    {
        $statsdExporterClient = new MemoryStatsdExporterClient($appName);

        $testObject = new TestObject();
        $testObject->setStatsdExporterClient($statsdExporterClient);
        $testObject->someCode();

        $statsdExporterClient->save();

        $metrics = $statsdExporterClient->getExportedMetrics();

        $firstMetric = current($metrics);
        $firstMetric->getName();
        $firstMetric->getUnit();
        $firstMetric->getValue();
        $firstMetric->getTags();
    }
}