|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Moon\Logger; |
|
6
|
|
|
|
|
7
|
|
|
use Moon\Logger\Handler\HandlerInterface; |
|
8
|
|
|
use Psr\Log\AbstractLogger; |
|
9
|
|
|
use Psr\Log\InvalidArgumentException; |
|
10
|
|
|
use Psr\Log\LogLevel; |
|
11
|
|
|
|
|
12
|
|
|
class Logger extends AbstractLogger |
|
13
|
|
|
{ |
|
14
|
|
|
/** |
|
15
|
|
|
* @var string Logger name |
|
16
|
|
|
*/ |
|
17
|
|
|
private $name; |
|
18
|
|
|
|
|
19
|
|
|
/** |
|
20
|
|
|
* @var HandlerInterface[] |
|
21
|
|
|
*/ |
|
22
|
|
|
private $handlers = []; |
|
23
|
|
|
|
|
24
|
|
|
/** |
|
25
|
|
|
* @var array Contains all accepted levels |
|
26
|
|
|
*/ |
|
27
|
|
|
private $levels = [ |
|
28
|
|
|
LogLevel::EMERGENCY, |
|
29
|
|
|
LogLevel::ALERT, |
|
30
|
|
|
LogLevel::CRITICAL, |
|
31
|
|
|
LogLevel::ERROR, |
|
32
|
|
|
LogLevel::WARNING, |
|
33
|
|
|
LogLevel::NOTICE, |
|
34
|
|
|
LogLevel::INFO, |
|
35
|
|
|
LogLevel::DEBUG, |
|
36
|
|
|
]; |
|
37
|
|
|
|
|
38
|
11 |
|
public function __construct(string $name, array $handlers) |
|
39
|
|
|
{ |
|
40
|
11 |
|
$this->name = $name; |
|
41
|
|
|
|
|
42
|
11 |
|
if (0 === \count($handlers)) { |
|
43
|
1 |
|
throw new InvalidArgumentException('At least one handler must be passed'); |
|
44
|
|
|
} |
|
45
|
|
|
|
|
46
|
10 |
|
foreach ($handlers as $key => $handler) { |
|
47
|
10 |
|
if (!$handler instanceof HandlerInterface) { |
|
48
|
1 |
|
throw new InvalidArgumentException( |
|
49
|
1 |
|
\sprintf('Handler must implement %s. Error with handler with key: %s', HandlerInterface::class, $key) |
|
50
|
|
|
); |
|
51
|
|
|
} |
|
52
|
9 |
|
$this->handlers[] = $handler; |
|
53
|
|
|
} |
|
54
|
9 |
|
} |
|
55
|
|
|
|
|
56
|
|
|
public function log($level, $message, array $context = []): void |
|
57
|
|
|
{ |
|
58
|
|
|
// throw an InvalidArgumentException if the level to log isn't in AbstractLogger |
|
59
|
|
|
if (!\in_array($level, $this->levels, true)) { |
|
60
|
6 |
|
throw new InvalidArgumentException(\sprintf( |
|
61
|
|
|
'The level MUST be one of the constants contained by the %s class. Given %s', LogLevel::class, $level |
|
62
|
|
|
)); |
|
63
|
6 |
|
} |
|
64
|
3 |
|
|
|
65
|
3 |
|
// throw an InvalidArgumentException if the message isn't an invalid format |
|
66
|
|
|
if (\is_array($message) || (\is_object($message) && !\method_exists($message, '__toString'))) { |
|
67
|
|
|
throw new InvalidArgumentException('Message must be a string or an object implementing __toString() method'); |
|
68
|
|
|
} |
|
69
|
|
|
|
|
70
|
3 |
|
// Pass the log to the handlers |
|
71
|
2 |
|
foreach ($this->handlers as $handler) { |
|
72
|
|
|
/* @var HandlerInterface $handler */ |
|
73
|
|
|
$handler->add($this->name, $level, $message, $context); |
|
74
|
|
|
} |
|
75
|
1 |
|
} |
|
76
|
|
|
} |
|
77
|
|
|
|