|
1
|
|
|
<?php |
|
2
|
|
|
/** |
|
3
|
|
|
* Spiral Framework. |
|
4
|
|
|
* |
|
5
|
|
|
* @license MIT |
|
6
|
|
|
* @author Anton Titov (Wolfy-J) |
|
7
|
|
|
*/ |
|
8
|
|
|
|
|
9
|
|
|
namespace Spiral\Debug\Traits; |
|
10
|
|
|
|
|
11
|
|
|
use Interop\Container\ContainerInterface; |
|
12
|
|
|
use Psr\Log\LoggerInterface; |
|
13
|
|
|
use Psr\Log\NullLogger; |
|
14
|
|
|
use Spiral\Debug\LogsInterface; |
|
15
|
|
|
|
|
16
|
|
|
/** |
|
17
|
|
|
* On demand logger creation. Allows class to share same logger between instances. Logger trait work |
|
18
|
|
|
* thought IoC scope! |
|
19
|
|
|
*/ |
|
20
|
|
|
trait LoggerTrait |
|
21
|
|
|
{ |
|
22
|
|
|
/** |
|
23
|
|
|
* Private and null. |
|
24
|
|
|
* |
|
25
|
|
|
* @internal |
|
26
|
|
|
* |
|
27
|
|
|
* @var LoggerInterface|null |
|
28
|
|
|
*/ |
|
29
|
|
|
private $logger = null; |
|
30
|
|
|
|
|
31
|
|
|
/** |
|
32
|
|
|
* Sets a logger. |
|
33
|
|
|
* |
|
34
|
|
|
* @param LoggerInterface $logger |
|
35
|
|
|
*/ |
|
36
|
1 |
|
public function setLogger(LoggerInterface $logger) |
|
37
|
|
|
{ |
|
38
|
1 |
|
$this->logger = $logger; |
|
39
|
1 |
|
} |
|
40
|
|
|
|
|
41
|
|
|
/** |
|
42
|
|
|
* Get associated or create new instance of LoggerInterface. |
|
43
|
|
|
* |
|
44
|
|
|
* @return LoggerInterface |
|
45
|
|
|
*/ |
|
46
|
9 |
|
protected function getLogger(): LoggerInterface |
|
47
|
|
|
{ |
|
48
|
9 |
|
if (!empty($this->logger)) { |
|
49
|
1 |
|
return $this->logger; |
|
50
|
|
|
} |
|
51
|
|
|
|
|
52
|
|
|
//We are using class name as log channel (name) by default |
|
53
|
8 |
|
return $this->logger = $this->createLogger(); |
|
54
|
|
|
} |
|
55
|
|
|
|
|
56
|
|
|
/** |
|
57
|
|
|
* Alias for "getLogger" function. |
|
58
|
|
|
* |
|
59
|
|
|
* @return LoggerInterface |
|
60
|
|
|
*/ |
|
61
|
3 |
|
protected function logger(): LoggerInterface |
|
62
|
|
|
{ |
|
63
|
3 |
|
return $this->getLogger(); |
|
64
|
|
|
} |
|
65
|
|
|
|
|
66
|
|
|
/** |
|
67
|
|
|
* @return ContainerInterface |
|
68
|
|
|
*/ |
|
69
|
|
|
abstract protected function iocContainer(); |
|
70
|
|
|
|
|
71
|
|
|
/** |
|
72
|
|
|
* Create new instance of associated logger (on demand creation). |
|
73
|
|
|
* |
|
74
|
|
|
* @return LoggerInterface |
|
75
|
|
|
*/ |
|
76
|
8 |
|
private function createLogger(): LoggerInterface |
|
77
|
|
|
{ |
|
78
|
8 |
|
$container = $this->iocContainer(); |
|
79
|
8 |
|
if (empty($container) || !$container->has(LogsInterface::class)) { |
|
80
|
7 |
|
return new NullLogger(); |
|
81
|
|
|
} |
|
82
|
|
|
|
|
83
|
|
|
//We are using class name as log channel (name) by default |
|
84
|
1 |
|
return $container->get(LogsInterface::class)->getLogger(static::class); |
|
85
|
|
|
} |
|
86
|
|
|
} |
|
87
|
|
|
|