-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathLogChannelManager.php
More file actions
106 lines (95 loc) · 2.78 KB
/
LogChannelManager.php
File metadata and controls
106 lines (95 loc) · 2.78 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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
<?php
namespace WebmanTech\Logger;
use InvalidArgumentException;
use WebmanTech\Logger\Mode\BaseMode;
use Monolog\Processor\ProcessorInterface;
class LogChannelManager
{
/**
* @var array
*/
protected $config = [
'channels' => [],
'modes' => [],
'levels' => [
'default' => 'info',
'special' => [],
],
'processors' => [],
];
public function __construct(array $config)
{
$this->config = array_merge($this->config, $config);
}
/**
* 对所有渠道构建适用于 config/log.php 下渠道配置的参数
* @return array
*/
public function buildLogChannelConfigs(): array
{
$channelConfigs = [];
foreach ($this->config['channels'] as $channel) {
$handlers = [];
foreach ($this->config['modes'] as $modeConfig) {
$mode = $this->buildMode($modeConfig);
if ($handler = $mode->getHandler($channel, $this->getLevel($channel))) {
$handlers[] = $handler;
}
}
if (count($handlers) <= 0) {
continue;
}
$channelConfigs[$channel] = [
'handlers' => $handlers,
'processors' => $this->buildProcessors(),
];
}
return $channelConfigs;
}
/**
* @var array
*/
private $_modes = [];
/**
* @param array $mode
* @return BaseMode
*/
protected function buildMode(array $mode): BaseMode
{
$class = $mode['class'];
if (!isset($this->_modes[$class])) {
$this->_modes[$class] = new $class($mode);
if (!$this->_modes[$class] instanceof BaseMode) {
throw new InvalidArgumentException('mode class 必须继承 BaseMode');
}
}
return $this->_modes[$class];
}
/**
* @return array
*/
protected function buildProcessors(): array
{
$processors = $this->config['processors'];
if (is_callable($processors)) {
$processors = call_user_func($processors);
}
if (!is_array($processors)) {
throw new InvalidArgumentException('processors 必须是数组或者 callable 返回数组');
}
foreach ($processors as $processor) {
if (!$processor instanceof ProcessorInterface) {
throw new InvalidArgumentException('processors 必须都是 ProcessorInterface 实例');
}
}
return $processors;
}
/**
* @param string $channel
* @return string
*/
protected function getLevel(string $channel): string
{
return $this->config['levels']['special'][$channel] ?? $this->config['levels']['default'];
}
}