1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
namespace Jellyfish\Log; |
6
|
|
|
|
7
|
|
|
use Monolog\Handler\AbstractProcessingHandler; |
8
|
|
|
use Monolog\Handler\RotatingFileHandler; |
9
|
|
|
use Monolog\Handler\StreamHandler; |
10
|
|
|
use Monolog\Logger; |
11
|
|
|
use Pimple\Container; |
12
|
|
|
use Pimple\ServiceProviderInterface; |
13
|
|
|
|
14
|
|
|
class LogServiceProvider implements ServiceProviderInterface |
15
|
|
|
{ |
16
|
|
|
public const CONTAINER_KEY_LOGGER = 'logger'; |
17
|
|
|
|
18
|
|
|
/** |
19
|
|
|
* @param \Pimple\Container $container |
20
|
|
|
* |
21
|
|
|
* @return void |
22
|
|
|
*/ |
23
|
|
|
public function register(Container $container): void |
24
|
|
|
{ |
25
|
|
|
$this->registerLogger($container); |
26
|
|
|
} |
27
|
|
|
|
28
|
|
|
/** |
29
|
|
|
* @param \Pimple\Container $container |
30
|
|
|
* |
31
|
|
|
* @return \Jellyfish\Log\LogServiceProvider |
32
|
|
|
*/ |
33
|
|
|
protected function registerLogger(Container $container): LogServiceProvider |
34
|
|
|
{ |
35
|
|
|
$self = $this; |
36
|
|
|
|
37
|
|
|
$container->offsetSet(static::CONTAINER_KEY_LOGGER, static function (Container $container) use ($self) { |
38
|
|
|
$logger = new Logger('jellyfish'); |
39
|
|
|
|
40
|
|
|
$logger->pushHandler($self->createStreamHandler($container)); |
41
|
|
|
$logger->pushHandler($self->createRotatingFileHandler($container)); |
42
|
|
|
|
43
|
|
|
return $logger; |
44
|
|
|
}); |
45
|
|
|
|
46
|
|
|
return $this; |
47
|
|
|
} |
48
|
|
|
|
49
|
|
|
/** |
50
|
|
|
* @param \Pimple\Container $container |
51
|
|
|
* |
52
|
|
|
* @return \Monolog\Handler\AbstractProcessingHandler |
53
|
|
|
* |
54
|
|
|
* @throws \Exception |
55
|
|
|
*/ |
56
|
|
|
protected function createStreamHandler(Container $container): AbstractProcessingHandler |
57
|
|
|
{ |
58
|
|
|
$logLevel = $container->offsetGet('config') |
59
|
|
|
->get(LogConstants::LOG_LEVEL, (string) LogConstants::DEFAULT_LOG_LEVEL); |
60
|
|
|
|
61
|
|
|
return new StreamHandler('php://stdout', (int) $logLevel); |
62
|
|
|
} |
63
|
|
|
|
64
|
|
|
/** |
65
|
|
|
* @param \Pimple\Container $container |
66
|
|
|
* |
67
|
|
|
* @return \Monolog\Handler\AbstractProcessingHandler |
68
|
|
|
*/ |
69
|
|
|
protected function createRotatingFileHandler(Container $container): AbstractProcessingHandler |
70
|
|
|
{ |
71
|
|
|
$logLevel = $container->offsetGet('config') |
72
|
|
|
->get(LogConstants::LOG_LEVEL, (string) LogConstants::DEFAULT_LOG_LEVEL); |
73
|
|
|
|
74
|
|
|
$filename = $container->offsetGet('root_dir') . 'var/log/jellyfish.log'; |
75
|
|
|
|
76
|
|
|
return new RotatingFileHandler($filename, 0, (int) $logLevel); |
77
|
|
|
} |
78
|
|
|
} |
79
|
|
|
|