forked from featurevisor/featurevisor-php
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLogger.php
More file actions
88 lines (73 loc) · 2.14 KB
/
Logger.php
File metadata and controls
88 lines (73 loc) · 2.14 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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
<?php
namespace Featurevisor;
use Closure;
use InvalidArgumentException;
use Psr\Log\LoggerInterface;
use Psr\Log\LoggerTrait;
use Psr\Log\LogLevel;
use Stringable;
class Logger implements LoggerInterface
{
use LoggerTrait;
private const MSG_PREFIX = '[Featurevisor]';
private const ALL_LEVELS = [
LogLevel::EMERGENCY,
LogLevel::ALERT,
LogLevel::CRITICAL,
LogLevel::ERROR,
LogLevel::WARNING,
LogLevel::NOTICE,
LogLevel::INFO,
LogLevel::DEBUG,
];
public const DEFAULT_LEVEL = LogLevel::INFO;
private string $level;
private Closure $handler;
/**
* @param array{
* level?: string,
* handler?: Closure,
* } $options
*/
public static function create(array $options = []): self
{
return new self(
$options['level'] ?? self::DEFAULT_LEVEL,
$options['handler'] ?? null
);
}
public function __construct(string $level = self::DEFAULT_LEVEL, Closure $handler = null)
{
$this->handler = $handler ?? static fn ($level, $message, array $context) => self::defaultLogHandler($level, $message, $context);
$this->level = $level;
}
public function setLevel(string $level): void
{
if (!in_array($level, self::ALL_LEVELS, true)) {
throw new InvalidArgumentException('Invalid log level');
}
$this->level = $level;
}
public function log($level, $message, array $context = []): void
{
$shouldHandle = array_search($this->level, self::ALL_LEVELS) >= array_search($level, self::ALL_LEVELS);
if (!$shouldHandle) {
return;
}
($this->handler)($level, self::MSG_PREFIX.' '.$message, $context);
}
private static function defaultLogHandler($level, $message, ?array $details = null): void
{
if (STDOUT == false) {
return;
}
fwrite(
STDOUT,
sprintf(
'%s %s',
$message,
$details !== null ? json_encode($details, JSON_THROW_ON_ERROR) : null
) . PHP_EOL
);
}
}