|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
declare(strict_types=1); |
|
4
|
|
|
|
|
5
|
|
|
namespace Yansongda\Pay\Service; |
|
6
|
|
|
|
|
7
|
|
|
use Monolog\Formatter\LineFormatter; |
|
8
|
|
|
use Monolog\Handler\AbstractProcessingHandler; |
|
9
|
|
|
use Monolog\Handler\RotatingFileHandler; |
|
10
|
|
|
use Monolog\Handler\StreamHandler; |
|
11
|
|
|
use Monolog\Logger; |
|
12
|
|
|
use Yansongda\Pay\Contract\ConfigInterface; |
|
13
|
|
|
use Yansongda\Pay\Contract\LoggerInterface; |
|
14
|
|
|
use Yansongda\Pay\Contract\ServiceProviderInterface; |
|
15
|
|
|
use Yansongda\Pay\Exception\ContainerException; |
|
16
|
|
|
use Yansongda\Pay\Exception\ServiceNotFoundException; |
|
17
|
|
|
use Yansongda\Pay\Pay; |
|
18
|
|
|
|
|
19
|
|
|
class LoggerServiceProvider implements ServiceProviderInterface |
|
20
|
|
|
{ |
|
21
|
|
|
protected array $config = [ |
|
22
|
|
|
'enable' => false, |
|
23
|
|
|
'file' => null, |
|
24
|
|
|
'identify' => 'yansongda.pay', |
|
25
|
|
|
'level' => Logger::DEBUG, |
|
26
|
|
|
'type' => 'daily', |
|
27
|
|
|
'max_files' => 30, |
|
28
|
|
|
'formatter' => "%datetime% > %channel%.%level_name% > %message% %context% %extra%\n\n", |
|
29
|
|
|
]; |
|
30
|
|
|
|
|
31
|
|
|
/** |
|
32
|
|
|
* @throws ContainerException |
|
33
|
|
|
* @throws ServiceNotFoundException |
|
34
|
|
|
*/ |
|
35
|
|
|
public function register(mixed $data = null): void |
|
36
|
|
|
{ |
|
37
|
|
|
/* @var ConfigInterface $config */ |
|
38
|
|
|
$config = Pay::get(ConfigInterface::class); |
|
39
|
|
|
|
|
40
|
|
|
$this->config = array_merge($this->config, $config->get('logger', [])); |
|
41
|
|
|
|
|
42
|
|
|
if (class_exists(Logger::class) && (true === ($this->config['enable'] ?? false))) { |
|
43
|
|
|
$logger = new Logger($this->config['identify']); |
|
44
|
|
|
|
|
45
|
|
|
$logger->pushHandler($this->getDefaultHandler() |
|
46
|
|
|
->setFormatter($this->getDefaultFormatter())); |
|
47
|
|
|
|
|
48
|
|
|
Pay::set(LoggerInterface::class, $logger); |
|
49
|
|
|
} |
|
50
|
|
|
} |
|
51
|
|
|
|
|
52
|
|
|
protected function getDefaultFormatter(): LineFormatter |
|
53
|
|
|
{ |
|
54
|
|
|
return new LineFormatter( |
|
55
|
|
|
$this->config['formatter'], |
|
56
|
|
|
null, |
|
57
|
|
|
false, |
|
58
|
|
|
true |
|
59
|
|
|
); |
|
60
|
|
|
} |
|
61
|
|
|
|
|
62
|
|
|
protected function getDefaultHandler(): AbstractProcessingHandler |
|
63
|
|
|
{ |
|
64
|
|
|
$file = $this->config['file'] ?? (sys_get_temp_dir().'/logs/'.$this->config['identify'].'.log'); |
|
65
|
|
|
|
|
66
|
|
|
return match ($this->config['type']) { |
|
67
|
|
|
'single' => new StreamHandler($file, $this->config['level']), |
|
68
|
|
|
default => new RotatingFileHandler($file, $this->config['max_files'], $this->config['level']), |
|
69
|
|
|
}; |
|
70
|
|
|
} |
|
71
|
|
|
} |
|
72
|
|
|
|