Lines 100.00% 22 / 22
Methods 100.00% 6 / 6
Classes 100.00% 1 / 1
Name Lines Methods CRAP
 __construct 100.00% 1 / 1 100.00% 1 / 1 1
 createStdoutLogger 100.00% 3 / 3 100.00% 1 / 1 1
 createDaemonLogger 100.00% 3 / 3 100.00% 1 / 1 1
 createLoggerFor 100.00% 4 / 4 100.00% 1 / 1 1
 createStreamHandler 100.00% 4 / 4 100.00% 1 / 1 1
 createFormatter 100.00% 7 / 7 100.00% 1 / 1 3
16final readonly class LoggerFactory
17{
18    private const string LINE_FORMAT = "%datetime% %level_name% %message% %context% %extra%\n";
19
20    private const string DAEMON_LINE_FORMAT = "%datetime% %level_name% [%extra.source%] %message% %context% %extra%\n";
21
22    private const string LINE_DATE_FORMAT = 'Y-m-d H:i:s.vP';
23
24    public function __construct(
25        private string $logStreamUrl = 'php://stdout',
26        private string $logFallbackStreamUrl = 'php://stderr',
27    ) {}
28
29    public function createStdoutLogger(LogLevel $level = LogLevel::Info, LogFormat $format = LogFormat::Line): LoggerInterface
30    {
31        $handler = $this->createStreamHandler(Level::fromName($level->name));
32        $handler->setFormatter($this->createFormatter($format, self::LINE_FORMAT));
33
34        return $this->createLoggerFor($handler);
35    }
36
37    // Every record reaches the filter, which applies the level of the app the record is about.
38    public function createDaemonLogger(LogVerbosityPolicy $verbosity, LogFormat $format = LogFormat::Line): LoggerInterface
39    {
40        $handler = $this->createStreamHandler(Level::Debug);
41        $handler->setFormatter($this->createFormatter($format, self::DAEMON_LINE_FORMAT));
42
43        return $this->createLoggerFor(new VerbosityFilterHandler($handler, $verbosity));
44    }
45
46    private function createLoggerFor(HandlerInterface $handler): LoggerInterface
47    {
48        return new Logger('stewart')
49            ->pushHandler($handler)
50            ->pushProcessor(new ExceptionContextProcessor())
51            ->pushProcessor(new ProcessTimeZoneProcessor());
52    }
53
54    private function createStreamHandler(Level $threshold): FallbackGroupHandler
55    {
56        // A failed write must not throw out of a log call, e.g. while the broker is stopping.
57        return new FallbackGroupHandler([
58            new StreamHandler($this->logStreamUrl, $threshold),
59            new StreamHandler($this->logFallbackStreamUrl, $threshold),
60        ]);
61    }
62
63    private function createFormatter(LogFormat $format, string $lineFormat): FormatterInterface
64    {
65        return match ($format) {
66            LogFormat::Json => new TraceLabelJsonFormatter(),
67            LogFormat::Line => new StackTraceLineFormatter(
68                format: $lineFormat,
69                dateFormat: self::LINE_DATE_FORMAT,
70                allowInlineLineBreaks: true,
71                ignoreEmptyContextAndExtra: true,
72            ),
73        };
74    }
75}