-
Notifications
You must be signed in to change notification settings - Fork 18
Expand file tree
/
Copy pathStderrLogger.php
More file actions
88 lines (71 loc) · 2.68 KB
/
Copy pathStderrLogger.php
File metadata and controls
88 lines (71 loc) · 2.68 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
declare(strict_types=1);
namespace SlackPhp\Framework;
use Psr\Log\{AbstractLogger, InvalidArgumentException, LogLevel};
use function json_encode;
class StderrLogger extends AbstractLogger
{
private const LOG_LEVEL_MAP = [
LogLevel::DEBUG => 0,
LogLevel::INFO => 1,
LogLevel::NOTICE => 2,
LogLevel::WARNING => 3,
LogLevel::ERROR => 4,
LogLevel::CRITICAL => 5,
LogLevel::ALERT => 6,
LogLevel::EMERGENCY => 7,
];
private int $minLevel;
/** @var resource */
private $stream;
public function __construct(string $minLevel = LogLevel::WARNING, $stream = 'php://stderr')
{
if (!isset(self::LOG_LEVEL_MAP[$minLevel])) {
throw new InvalidArgumentException("Invalid log level: {$minLevel}");
}
$this->minLevel = self::LOG_LEVEL_MAP[$minLevel];
if (is_resource($stream)) {
$this->stream = $stream;
} elseif (is_string($stream)) {
$this->stream = fopen($stream, 'a');
if (!$this->stream) {
throw new Exception('Unable to open stream: ' . $stream);
}
} else {
throw new InvalidArgumentException('A stream must either be a resource or a string');
}
}
public function log($level, $message, array $context = []): void
{
if (!is_string($level)) {
if (is_object($level) && method_exists($level, '__toString')) {
$level = (string) $level;
} else {
throw new InvalidArgumentException('Invalid log level: must be a string');
}
}
if (!isset(self::LOG_LEVEL_MAP[$level])) {
throw new InvalidArgumentException("Invalid log level: {$level}");
}
// Don't report logs for log levels less than the min level.
if (self::LOG_LEVEL_MAP[$level] < $this->minLevel) {
return;
}
// Apply special formatting for "exception" fields.
if (isset($context['exception'])) {
$exception = $context['exception'];
if ($exception instanceof Exception) {
$context = $exception->getContext() + $context;
}
$context['exception'] = explode("\n", (string) $exception);
}
if (!is_string($message)) {
if (is_object($message) && method_exists($message, '__toString')) {
$message = (string) $message;
} else {
throw new InvalidArgumentException('Invalid log message: must be a string');
}
}
fwrite($this->stream, json_encode(compact('level', 'message', 'context')) . "\n");
}
}