1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace RemotelyLiving\PHPQueryBus\Middleware; |
6
|
|
|
|
7
|
|
|
use Psr\Log; |
8
|
|
|
use RemotelyLiving\PHPQueryBus\Interfaces; |
9
|
|
|
use RemotelyLiving\PHPQueryBus\Enums; |
10
|
|
|
use RemotelyLiving\PHPQueryBus\Traits; |
11
|
|
|
|
12
|
|
|
final class PerfBudgetLogger implements Log\LoggerAwareInterface |
13
|
|
|
{ |
14
|
|
|
use Traits\Logger; |
15
|
|
|
|
16
|
|
|
private int $thresholdSeconds; |
17
|
|
|
|
18
|
|
|
private float $thresholdMemoryMB; |
19
|
|
|
|
20
|
|
|
private Enums\LogLevel $logLevel; |
21
|
|
|
|
22
|
|
|
public function __construct( |
23
|
|
|
int $thresholdSeconds = 10, |
24
|
|
|
float $thresholdMemoryMB = 10.0, |
25
|
|
|
Enums\LogLevel $logLevel = null |
26
|
|
|
) { |
27
|
|
|
$this->thresholdSeconds = $thresholdSeconds; |
28
|
|
|
$this->thresholdMemoryMB = $thresholdMemoryMB; |
29
|
|
|
$this->logLevel = $logLevel ?? Enums\LogLevel::WARNING(); |
30
|
|
|
} |
31
|
|
|
|
32
|
|
|
public function __invoke(object $query, callable $next): Interfaces\Result |
33
|
|
|
{ |
34
|
|
|
$startTime = microtime(true); |
35
|
|
|
$startMemoryBytes = memory_get_usage(true); |
36
|
|
|
$result = $next($query); |
37
|
|
|
$totalTime = (float) microtime(true) - $startTime; |
38
|
|
|
$totalMegabytesIncrease = (memory_get_peak_usage(true) - $startMemoryBytes) / 1000000; |
39
|
|
|
|
40
|
|
|
if ($this->isOverThresholds($totalTime, $totalMegabytesIncrease)) { |
41
|
|
|
$this->getLogger()->log( |
42
|
|
|
(string) $this->logLevel, |
43
|
|
|
'Performance threshold exceeded', |
44
|
|
|
['MB' => $totalMegabytesIncrease, 'seconds' => $totalTime, 'query' => get_class($query) ] |
45
|
|
|
); |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
return $result; |
49
|
|
|
} |
50
|
|
|
|
51
|
|
|
private function isOverThresholds(float $seconds, float $megaBytes): bool |
52
|
|
|
{ |
53
|
|
|
return ($seconds > $this->thresholdSeconds || ($megaBytes) > $this->thresholdMemoryMB); |
54
|
|
|
} |
55
|
|
|
} |
56
|
|
|
|