-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLogEvent.php
More file actions
63 lines (55 loc) · 1.91 KB
/
LogEvent.php
File metadata and controls
63 lines (55 loc) · 1.91 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
<?php
declare(strict_types=1);
namespace Arcp\Messages\Telemetry;
use Arcp\Envelope\MessageType;
use Arcp\Errors\InvalidArgumentException;
/** RFC §17.2 — structured log line. */
final readonly class LogEvent extends MessageType
{
public const array LEVELS = ['trace', 'debug', 'info', 'warn', 'error', 'critical'];
/** @param array<string, mixed> $attributes */
public function __construct(
public string $level,
public string $message,
public array $attributes = [],
) {
if (!\in_array($level, self::LEVELS, true)) {
throw new InvalidArgumentException('log.level must be one of ' . implode(',', self::LEVELS));
}
if ($message === '') {
throw new InvalidArgumentException('log.message must be non-empty');
}
}
#[\Override]
public static function typeName(): string
{
return 'log';
}
#[\Override]
public function toArray(): array
{
$out = ['level' => $this->level, 'message' => $this->message];
if ($this->attributes !== []) {
$out['attributes'] = $this->attributes;
}
return $out;
}
#[\Override]
public static function fromArray(array $data): static
{
$level = $data['level'] ?? throw new InvalidArgumentException('level missing');
$msg = $data['message'] ?? throw new InvalidArgumentException('message missing');
if (!\is_string($level) || !\is_string($msg)) {
throw new InvalidArgumentException('level/message must be strings');
}
$attrs = [];
if (isset($data['attributes'])) {
if (!\is_array($data['attributes'])) {
throw new InvalidArgumentException('attributes must be object');
}
/** @var array<string, mixed> $attrs */
$attrs = $data['attributes'];
}
return new static($level, $msg, $attrs);
}
}