Lines 100.00% 39 / 39
Methods 100.00% 8 / 8
Classes 100.00% 1 / 1
Name Lines Methods CRAP
 __construct 100.00% 1 / 1 100.00% 1 / 1 1
 forApp 100.00% 1 / 1 100.00% 1 / 1 1
 forScope 100.00% 1 / 1 100.00% 1 / 1 1
 log 100.00% 9 / 9 100.00% 1 / 1 5
 recordTrace 100.00% 1 / 1 100.00% 1 / 1 1
 sendRecord 100.00% 10 / 10 100.00% 1 / 1 3
 serializableContext 100.00% 4 / 4 100.00% 1 / 1 2
 serializableValue 100.00% 12 / 12 100.00% 1 / 1 6
19final class WorkerLogger extends AbstractLogger
20{
21    public function __construct(
22        private readonly Transport $transport,
23        private readonly StderrFallback $stderr,
24        private readonly ResourceScope $resourceScope,
25        private readonly LogVerbosityPolicy $verbosity,
26    ) {}
27
28    public function forApp(AppId $appId): self
29    {
30        return $this->forScope(ResourceScope::forApp($appId));
31    }
32
33    public function forScope(ResourceScope $resourceScope): self
34    {
35        return new self($this->transport, $this->stderr, $resourceScope, $this->verbosity);
36    }
37
38    /**
39     * @param mixed $level
40     * @param array<mixed> $context
41     * @throws InvalidArgumentException
42     */
43    public function log($level, string|Stringable $message, array $context = []): void
44    {
45        $severity = \is_string($level) ? LogLevel::tryFrom($level) : null;
46
47        if ($severity === null) {
48            throw new InvalidArgumentException(\sprintf(
49                'Unknown log level "%s"; use one of %s.',
50                \is_scalar($level) ? (string) $level : get_debug_type($level),
51                implode(', ', array_map(static fn(LogLevel $known): string => $known->value, LogLevel::cases())),
52            ));
53        }
54
55        if ($this->verbosity->admitsLevel($severity, $this->resourceScope)) {
56            $this->sendRecord($severity, (string) $message, $context, trace: false);
57        }
58    }
59
60    // Callers check LogVerbosityPolicy::isTracing() first, so a trace passes whatever the level says.
61    /** @param array<mixed> $context */
62    public function recordTrace(string $message, array $context = []): void
63    {
64        $this->sendRecord(LogLevel::Debug, $message, $context, trace: true);
65    }
66
67    /** @param array<mixed> $context */
68    private function sendRecord(LogLevel $severity, string $message, array $context, bool $trace): void
69    {
70        try {
71            $this->transport->send(new LogRecord(
72                scope: $this->resourceScope,
73                level: $severity,
74                message: $message,
75                context: self::serializableContext($context),
76                exception: ($context['exception'] ?? null) instanceof Throwable ? ExceptionDetails::fromThrowable($context['exception']) : null,
77                trace: $trace,
78            ));
79        } catch (Throwable) {
80            $this->stderr->writeLine($this->resourceScope, \sprintf('%s %s', $severity->value, $message));
81        }
82    }
83
84    /**
85     * @param array<array-key, mixed> $context
86     * @return array<string, mixed>
87     */
88    private static function serializableContext(array $context): array
89    {
90        $out = [];
91
92        foreach ($context as $key => $value) {
93            $out[(string) $key] = self::serializableValue($value);
94        }
95
96        return $out;
97    }
98
99    private static function serializableValue(mixed $value): mixed
100    {
101        return match (true) {
102            $value === null, \is_scalar($value) => $value,
103            $value instanceof Throwable => \sprintf(
104                "%s: %s in %s:%d\n%s",
105                $value::class,
106                $value->getMessage(),
107                $value->getFile(),
108                $value->getLine(),
109                $value->getTraceAsString(),
110            ),
111            \is_array($value) => array_map(self::serializableValue(...), $value),
112            $value instanceof Stringable => (string) $value,
113            default => get_debug_type($value),
114        };
115    }
116}