Passed
Push — master ( 1c24a5...c12de4 )
by Eugene
03:23
created

SlowRequestHandler::isHandling()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4
Code Lines 1

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 1
dl 0
loc 4
rs 10
c 0
b 0
f 0
cc 1
nc 1
nop 1
1
<?php
2
3
/**
4
 * This file is part of the Tarantool Client package.
5
 *
6
 * (c) Eugene Leonovich <[email protected]>
7
 *
8
 * For the full copyright and license information, please view the LICENSE
9
 * file that was distributed with this source code.
10
 */
11
12
declare(strict_types=1);
13
14
namespace App;
15
16
use Monolog\Handler\HandlerInterface;
17
use Monolog\Handler\HandlerWrapper;
18
use Monolog\Logger;
19
use Tarantool\Client\RequestTypes;
20
21
final class SlowRequestHandler extends HandlerWrapper
22
{
23
    private $thresholdMs;
24
    private $level;
25
26
    public function __construct(HandlerInterface $handler, int $thresholdMs, int $level = Logger::WARNING)
27
    {
28
        parent::__construct($handler);
29
30
        $this->thresholdMs = $thresholdMs;
31
        $this->level = $level;
32
    }
33
34
    public function isHandling(array $record) : bool
35
    {
36
        // capture all levels
37
        return true;
38
    }
39
40
    public function handle(array $record) : bool
41
    {
42
        if (!isset($record['context']['duration_ms'], $record['context']['request'])) {
43
            return false;
44
        }
45
46
        if ($record['context']['duration_ms'] <= $this->thresholdMs) {
47
            return false;
48
        }
49
50
        $request = $record['context']['request'];
51
52
        return $this->handler->handle([
53
            'level' => $this->level,
54
            'level_name' => Logger::getLevelName($this->level),
55
            'message' => sprintf('Slow %s request detected (%d ms)', RequestTypes::getName($request->getType()), $record['context']['duration_ms']),
56
            'context' => ['request_body' => $request->getBody()],
57
        ] + $record);
58
    }
59
}
60