Lines 92.30% 12 / 13
Functions and Methods 83.33% 5 / 6
Classes and Traits 0.00% 0 / 1
Name Lines Functions and Methods CRAP Classes and Traits
VerbosityFilterHandler 92.30% 12 / 13 83.33% 5 / 6 10.05 0.00% 0 / 1
 __construct 100.00% 1 / 1 100.00% 1 / 1 1
 isHandling 100.00% 1 / 1 100.00% 1 / 1 2
 handle 100.00% 1 / 1 100.00% 1 / 1 2
 handleBatch 0.00% 0 / 1 0.00% 0 / 1 2
 admitsRecord 100.00% 2 / 2 100.00% 1 / 1 2
 labelWithSource 100.00% 7 / 7 100.00% 1 / 1 2
1<?php
2
3declare(strict_types=1);
4
5namespace Stewart\Runtime\Logging;
6
7use Monolog\Handler\HandlerInterface;
8use Monolog\Handler\HandlerWrapper;
9use Monolog\LogRecord;
10use Stewart\Runtime\Model\LogLevel;
11
12// Monolog asks isHandling() only before the first handler runs, so handle() must decide again.
13final class VerbosityFilterHandler extends HandlerWrapper
14{
15    public function __construct(
16        HandlerInterface $handler,
17        private readonly LogVerbosityPolicy $verbosity,
18    ) {
19        parent::__construct($handler);
20    }
21
22    public function isHandling(LogRecord $record): bool
23    {
24        return $this->admitsRecord($record) && parent::isHandling($record);
25    }
26
27    public function handle(LogRecord $record): bool
28    {
29        return $this->admitsRecord($record) && parent::handle($this->labelWithSource($record));
30    }
31
32    /** @param array<LogRecord> $records */
33    public function handleBatch(array $records): void
34    {
35        parent::handleBatch(array_map($this->labelWithSource(...), array_values(array_filter($records, $this->admitsRecord(...)))));
36    }
37
38    // A trace record is built only for a traced app, so it passes whatever the level says.
39    private function admitsRecord(LogRecord $record): bool
40    {
41        $origin = LogOrigin::findInContext($record->context);
42
43        return $origin?->traced === true || $this->verbosity->admitsLevel(LogLevel::from($record->level->toPsrLogLevel()), $origin?->scope);
44    }
45
46    private function labelWithSource(LogRecord $record): LogRecord
47    {
48        $origin = LogOrigin::findInContext($record->context) ?? LogOrigin::broker();
49        $context = $record->context;
50        unset($context[LogOrigin::CONTEXT_KEY]);
51
52        $extra = [...$record->extra, LogOrigin::SOURCE_KEY => $origin->label];
53
54        if ($origin->traced) {
55            $extra[LogOrigin::TRACE_KEY] = true;
56        }
57
58        return $record->with(context: $context, extra: $extra);
59    }
60}