1
|
|
|
<?php
|
2
|
|
|
namespace yrc\components\log;
|
3
|
|
|
|
4
|
|
|
use Psr\Log\LoggerAwareInterface;
|
5
|
|
|
use Psr\Log\LoggerAwareTrait;
|
6
|
|
|
use Psr\Log\LoggerInterface;
|
7
|
|
|
use Psr\Log\LogLevel;
|
8
|
|
|
use yii\base\InvalidConfigException;
|
9
|
|
|
use yii\helpers\VarDumper;
|
10
|
|
|
use yii\log\Logger;
|
11
|
|
|
use yii\log\Target;
|
12
|
|
|
|
13
|
|
|
/**
|
14
|
|
|
* PSRTarget is a log target which passes messages to PSR-3 compatible logger.
|
15
|
|
|
*/
|
16
|
|
|
class PsrTarget extends Target implements LoggerAwareInterface
|
17
|
|
|
{
|
18
|
|
|
use LoggerAwareTrait;
|
19
|
|
|
|
20
|
|
|
private $_psrLevels = [
|
21
|
|
|
Logger::LEVEL_ERROR => LogLevel::ERROR,
|
22
|
|
|
Logger::LEVEL_WARNING => LogLevel::WARNING,
|
23
|
|
|
Logger::LEVEL_INFO => LogLevel::INFO,
|
24
|
|
|
Logger::LEVEL_TRACE => LogLevel::DEBUG,
|
25
|
|
|
Logger::LEVEL_PROFILE => LogLevel::DEBUG,
|
26
|
|
|
Logger::LEVEL_PROFILE_BEGIN => LogLevel::DEBUG,
|
27
|
|
|
Logger::LEVEL_PROFILE_END => LogLevel::DEBUG,
|
28
|
|
|
];
|
29
|
|
|
|
30
|
|
|
/**
|
31
|
|
|
* @return LoggerInterface
|
32
|
|
|
* @throws InvalidConfigException
|
33
|
|
|
*/
|
34
|
|
|
public function getLogger()
|
35
|
|
|
{
|
36
|
|
|
if ($this->logger === null) {
|
37
|
|
|
throw new InvalidConfigException('Logger should be configured with Psr\Log\LoggerInterface.');
|
38
|
|
|
}
|
39
|
|
|
return $this->logger;
|
40
|
|
|
}
|
41
|
|
|
|
42
|
|
|
/**
|
43
|
|
|
* @inheritdoc
|
44
|
|
|
*/
|
45
|
|
|
public function export()
|
46
|
|
|
{
|
47
|
|
|
foreach ($this->messages as $message) {
|
48
|
|
|
$context = [];
|
49
|
|
|
if (isset($message[4])) {
|
50
|
|
|
$context['trace'] = $message[4];
|
51
|
|
|
}
|
52
|
|
|
|
53
|
|
|
if (isset($message[5])) {
|
54
|
|
|
$context['memory'] = $message[5];
|
55
|
|
|
}
|
56
|
|
|
|
57
|
|
|
if (isset($message[2])) {
|
58
|
|
|
$context['category'] = $message[2];
|
59
|
|
|
}
|
60
|
|
|
|
61
|
|
|
$text = $message[0];
|
62
|
|
|
|
63
|
|
|
if (!is_string($text)) {
|
64
|
|
|
// exceptions may not be serializable if in the call stack somewhere is a Closure
|
65
|
|
|
if ($text instanceof \Throwable || $text instanceof \Exception) {
|
66
|
|
|
$text = (string)$text;
|
67
|
|
|
} else if (\is_array($text)) {
|
68
|
|
|
$ctx = $text;
|
69
|
|
|
if (isset($ctx['message'])) {
|
70
|
|
|
$text = $ctx['message'];
|
71
|
|
|
unset($ctx['message']);
|
72
|
|
|
foreach ($ctx as $k => $v) {
|
73
|
|
|
$context[$k] = $v;
|
74
|
|
|
}
|
75
|
|
|
} else {
|
76
|
|
|
$text = VarDumper::export($text);
|
77
|
|
|
}
|
78
|
|
|
} else {
|
79
|
|
|
$text = VarDumper::export($text);
|
80
|
|
|
}
|
81
|
|
|
}
|
82
|
|
|
|
83
|
|
|
$this->getLogger()->log($this->_psrLevels[$message[1]], $text, $context);
|
84
|
|
|
}
|
85
|
|
|
}
|
86
|
|
|
}
|
87
|
|
|
|