Skip to content

Commit

Permalink
added new version of runtime counters
Browse files Browse the repository at this point in the history
  • Loading branch information
demidovich committed Aug 25, 2023
1 parent 7345764 commit 48cc67d
Show file tree
Hide file tree
Showing 11 changed files with 260 additions and 205 deletions.
5 changes: 4 additions & 1 deletion composer.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,10 @@
"autoload-dev": {
"psr-4": {
"Tests\\": "tests/"
}
},
"files": [
"src/helpers.php"
]
},
"require": {
"php": ">=8.1",
Expand Down
13 changes: 8 additions & 5 deletions example/AppMetrics.php
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
<?php

use Metrics\Metrics;
use Metrics\Timer;

/**
* Wrappers of your counters and timers
*/
class AppMetrics extends Metrics
{
protected $namespace = 'myapp';
protected $namespace = "myapp";

/**
* Register spent time from database query event or etc
Expand All @@ -17,7 +18,9 @@ class AppMetrics extends Metrics
*/
public function spentSql(int $microseconds): void
{
$this->runtime()->spent('sql', (int) $microseconds * 1000);
$timer = Timer::stoppedFromMicroseconds("sql", $microseconds);

$this->runtime()->spent($timer);
}

/**
Expand All @@ -27,7 +30,7 @@ public function spentSql(int $microseconds): void
*/
public function startRedis(): void
{
$this->runtime()->start('redis');
$this->runtime()->start("redis");
}

/**
Expand All @@ -37,7 +40,7 @@ public function startRedis(): void
*/
public function startRemoteCall(): void
{
$this->runtime()->start('remote_call');
$this->runtime()->start("remote_call");
}

/**
Expand All @@ -47,6 +50,6 @@ public function startRemoteCall(): void
*/
public function registerSigninAttempt(): void
{
$this->counters()->increase('signin_attempt');
$this->counters()->increase("signin_attempt");
}
}
38 changes: 19 additions & 19 deletions example/index.php
Original file line number Diff line number Diff line change
@@ -1,46 +1,46 @@
<?php

define('APP_START_TIME', hrtime(true));
define("APP_START_TIME", hrtime(true));

require __DIR__.'/../vendor/autoload.php';
require __DIR__.'/AppMetrics.php';
require __DIR__."/../vendor/autoload.php";
require __DIR__."/AppMetrics.php";

$metrics = new AppMetrics(APP_START_TIME, ['app_node' => '10.0.0.1']);
$metrics = new AppMetrics(APP_START_TIME, ["app_node" => "10.0.0.1"]);
$metrics->initStorage(
Metrics\Storage::create('redis', ['host' => 'redis'])
Metrics\Storage::create("redis", ["host" => "redis"])
);

// PHP initialization completed
// Start of business logic
$metrics->startPhp();

switch ($_SERVER['REQUEST_URI']) {
switch ($_SERVER["REQUEST_URI"]) {

case '/':
$metrics->setHttpMethod('get');
$metrics->setHttpRoute('index@index');
echo 'index';
case "/":
$metrics->setHttpMethod("get");
$metrics->setHttpRoute("index@index");
echo "index";
$metrics->setHttpStatus(200);
break;

case '/books':
$metrics->setHttpMethod('get');
$metrics->setHttpRoute('api.books@read');
case "/books":
$metrics->setHttpMethod("get");
$metrics->setHttpRoute("api.books@read");
echo appApiResourceReadHandler($metrics);
$metrics->setHttpStatus(200);
break;

case '/metrics':
$metrics->setHttpMethod('get');
$metrics->setHttpRoute('metrics');
case "/metrics":
$metrics->setHttpMethod("get");
$metrics->setHttpRoute("metrics");
header("Content-Type: text/plain");
echo exportMetricsHandler($metrics);
$metrics->setHttpStatus(200);
break;

default:
$metrics->setHttpMethod('get');
$metrics->setHttpRoute('error');
$metrics->setHttpMethod("get");
$metrics->setHttpRoute("error");
$metrics->setHttpStatus(404);

}
Expand Down Expand Up @@ -75,7 +75,7 @@ function appApiResourceReadHandler(AppMetrics $metrics)
// If Metrics\Storage has been initialized all metrics will be persisted
// with register_shutdown_function()

return 'books';
return "books";
}

function exportMetricsHandler(AppMetrics $metrics)
Expand Down
6 changes: 3 additions & 3 deletions src/Metrics/Debug.php
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,9 @@ public function toLog(Metrics $metrics): void
$memory = $metrics->memoryUsage();
$labels = $metrics->labels()->all();
$counters = $metrics->counters()->all();
$timers = $metrics->runtime()->allInSeconds();
$timers = $metrics->runtime()->fetchResultsInSeconds();

$timers['total'] = array_sum($timers);
$timers["total"] = array_sum($timers);

$debug = PHP_EOL;
$debug .= "#" . PHP_EOL;
Expand All @@ -31,7 +31,7 @@ public function toLog(Metrics $metrics): void
$debug .= "method : " . $metrics->httpMethod() . PHP_EOL;
$debug .= "route : " . $metrics->httpRoute() . PHP_EOL;
$debug .= "status : " . $metrics->httpStatus() . PHP_EOL;
$debug .= "memory : " . round($memory / (1024 * 1024), 2) . 'Mb' . PHP_EOL;
$debug .= "memory : " . round($memory / (1024 * 1024), 2) . "Mb" . PHP_EOL;
$debug .= "labels : " . print_r($labels, true) . PHP_EOL;
$debug .= "timers : " . print_r($timers, true) . PHP_EOL;
$debug .= "counters : " . print_r($counters, true) . PHP_EOL;
Expand Down
10 changes: 5 additions & 5 deletions src/Metrics/Metrics.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,10 @@

class Metrics
{
protected $namespace = 'app';
protected $namespace = "app";

private $httpRoute = 'undefined';
private $httpMethod = 'undefined';
private $httpRoute = "undefined";
private $httpMethod = "undefined";
private $httpStatus = 0;
private $labels;
private $runtime;
Expand Down Expand Up @@ -48,14 +48,14 @@ public function initStorage(Storage $storage): void
{
$this->storage = $storage;

register_shutdown_function([$storage, 'persist'], $this);
register_shutdown_function([$storage, "persist"], $this);
}

public function initDebug(LoggerInterface $logger): void
{
$debug = new Debug($logger);

register_shutdown_function([$debug, 'toLog'], $this);
register_shutdown_function([$debug, "toLog"], $this);
}

public function setHttpRoute(string $value): void
Expand Down
94 changes: 25 additions & 69 deletions src/Metrics/Runtime.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,39 +4,19 @@

class Runtime
{
public const PHP_INIT = 'php_init';
public const PHP = 'php';
public const PHP_INIT = "php_init";
public const PHP = "php";

private $timer;
private $timerStartedAt;
private Timer $timer;

private $timers = [];
private array $timers = [];

/**
* @param int $startTime Application start time in nanoseconds
*/
public function __construct(int $startTime)
public function __construct(int $startNanosecondsTime)
{
$this->timer = self::PHP_INIT;
$this->timerStartedAt = $startTime;

$this->timers[self::PHP_INIT] = 0;
}

/**
* Active timer
*/
public function timer(): string
{
return $this->timer;
}

/**
* Active timer start time
*/
public function timerStartedAt()
{
return $this->timerStartedAt;
$this->timer = new Timer(self::PHP_INIT, $startNanosecondsTime);
}

/**
Expand All @@ -46,61 +26,37 @@ public function timerStartedAt()
*/
public function start(string $timer): void
{
if ($timer === $this->timer) {
if ($timer === $this->timer->name) {
return;
}

if (! isset($this->timers[$timer])) {
$this->timers[$timer] = 0;
}

$this->stop();
$this->timer = $timer;
}

/**
* Stop active timer
* @return int
*/
public function stop(): void
{
$finishedAt = hrtime(true);

$this->timers[$this->timer] += ($finishedAt - $this->timerStartedAt);

$this->timerStartedAt = $finishedAt;
$this->timer->stop();
$this->timers[] = $this->timer;
$this->timer = Timer::new($timer);
}

public function spent(string $timer, int $nanoseconds): void
public function spent(Timer $timer): void
{
$runningTimer = $this->timer;

$this->timers[$runningTimer] = $this->timers[$runningTimer] - $nanoseconds;
$this->timer->subTime($timer);

if (! isset($this->timers[$timer])) {
$this->timers[$timer] = 0;
}

$this->timers[$timer] += $nanoseconds;
$this->timers[] = $timer;
}

public function allInSeconds(int $precision = 6): array
public function fetchResultsInSeconds(int $precision = 6): array
{
return $this->timers(1e9, $precision);
}
$this->timer->stop();
$this->timers[] = $this->timer;

public function allInMilliseconds(int $precision = 2): array
{
return $this->timers(1e6, $precision);
}

private function timers(int $divider, int $precision): array
{
$result = [];
foreach ($this->timers as $name => $value) {
$result[$name] = \round($value / $divider, $precision);
$results = [];
/** @var Timer $timer */
foreach ($this->timers as $timer) {
if (! isset($results[$timer->name])) {
$results[$timer->name] = $timer->toSeconds($precision);
} else {
$results[$timer->name] += $timer->toSeconds($precision);
}
}

return $result;
return $results;
}
}
Loading

0 comments on commit 48cc67d

Please sign in to comment.