1 | <?php |
||
12 | trait Logging |
||
13 | { |
||
14 | /** |
||
15 | * @var LoggerInterface |
||
16 | */ |
||
17 | protected $logger; |
||
18 | |||
19 | |||
20 | /** |
||
21 | * Get the log level for an error code |
||
22 | * |
||
23 | * @param int $code E_* error code |
||
24 | * @return string |
||
25 | */ |
||
26 | abstract protected function getLogLevel($code = null); |
||
27 | |||
28 | /** |
||
29 | * Turn an error code into a string |
||
30 | * |
||
31 | * @param int $code |
||
32 | * @return string |
||
33 | */ |
||
34 | abstract protected function codeToString($code); |
||
35 | |||
36 | |||
37 | /** |
||
38 | * Set the logger for logging errors |
||
39 | * |
||
40 | * @param LoggerInterface $logger |
||
41 | */ |
||
42 | 116 | public function setLogger(LoggerInterface $logger) |
|
46 | |||
47 | /** |
||
48 | * Set the logger for logging errors |
||
49 | * |
||
50 | * @return LoggerInterface |
||
51 | */ |
||
52 | 70 | public function getLogger() |
|
53 | { |
||
54 | 70 | if (!isset($this->logger)) { |
|
55 | 8 | $this->logger = new NullLogger(); |
|
56 | } |
||
57 | |||
58 | 70 | return $this->logger; |
|
59 | } |
||
60 | |||
61 | |||
62 | /** |
||
63 | * Log an error or exception |
||
64 | * |
||
65 | * @param \Exception|\Error $error |
||
66 | */ |
||
67 | 68 | public function log($error) |
|
80 | |||
81 | /** |
||
82 | * Log an error |
||
83 | * |
||
84 | * @param \Error|\ErrorException $error |
||
85 | */ |
||
86 | 52 | protected function logError($error) |
|
87 | { |
||
88 | 52 | $code = $error instanceof \ErrorException ? $error->getSeverity() : E_ERROR; |
|
89 | 52 | $level = $this->getLogLevel($code); |
|
90 | |||
91 | 52 | $message = sprintf('%s: %s at %s line %s', $this->codeToString($code), $error->getMessage(), |
|
92 | 52 | $error->getFile(), $error->getLine()); |
|
93 | |||
94 | $context = [ |
||
95 | 52 | 'error' => $error, |
|
96 | 52 | 'code' => $code, |
|
97 | 52 | 'message' => $error->getMessage(), |
|
98 | 52 | 'file' => $error->getFile(), |
|
99 | 52 | 'line' => $error->getLine() |
|
100 | ]; |
||
101 | |||
102 | 52 | $this->getLogger()->log($level, $message, $context); |
|
103 | 52 | } |
|
104 | |||
105 | /** |
||
106 | * Log an exception |
||
107 | * |
||
108 | * @param \Exception $exception |
||
109 | */ |
||
110 | 12 | protected function logException(\Exception $exception) |
|
121 | } |
||
122 |