1
|
|
|
<?php |
2
|
|
|
declare(strict_types=1); |
3
|
|
|
/** |
4
|
|
|
* Minotaur |
5
|
|
|
* |
6
|
|
|
* Licensed under the Apache License, Version 2.0 (the "License"); you may not |
7
|
|
|
* use this file except in compliance with the License. You may obtain a copy of |
8
|
|
|
* the License at |
9
|
|
|
* |
10
|
|
|
* http://www.apache.org/licenses/LICENSE-2.0 |
11
|
|
|
* |
12
|
|
|
* Unless required by applicable law or agreed to in writing, software |
13
|
|
|
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT |
14
|
|
|
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the |
15
|
|
|
* License for the specific language governing permissions and limitations under |
16
|
|
|
* the License. |
17
|
|
|
* |
18
|
|
|
* @copyright 2015-2017 Appertly |
19
|
|
|
* @license Apache-2.0 |
20
|
|
|
*/ |
21
|
|
|
namespace Minotaur; |
22
|
|
|
|
23
|
|
|
use Psr\Log\LoggerInterface as Logger; |
24
|
|
|
use Psr\Log\LogLevel; |
25
|
|
|
|
26
|
|
|
/** |
27
|
|
|
* Responsible for logging exceptions |
28
|
|
|
*/ |
29
|
|
|
class ErrorLogger implements \Psr\Log\LoggerAwareInterface |
30
|
|
|
{ |
31
|
|
|
use \Psr\Log\LoggerAwareTrait; |
32
|
|
|
|
33
|
|
|
/** |
34
|
|
|
* @var array<string,string> Stores the Exception class name to log level |
35
|
|
|
*/ |
36
|
|
|
private $levels; |
37
|
|
|
|
38
|
|
|
/** |
39
|
|
|
* Creates a new ErrorLogger. |
40
|
|
|
* |
41
|
|
|
* If an exception isn't found in the `$levels` map, this class assumes a |
42
|
|
|
* level of `LogLevel::ERROR`. |
43
|
|
|
* |
44
|
|
|
* ```php |
45
|
|
|
* $elog = new ErrorLogger( |
46
|
|
|
* $logger, |
47
|
|
|
* ["MyException" => LogLevel::DEBUG, "RuntimeException" => LogLevel::WARN] |
48
|
|
|
* ); |
49
|
|
|
* ``` |
50
|
|
|
* |
51
|
|
|
* @param $logger - The logger; will use `Psr\Log\NullLogger` by default |
52
|
|
|
* @param $levels - Map of Exception names to log levels. Order matters! |
53
|
|
|
*/ |
54
|
1 |
|
public function __construct(Logger $logger = null, array $levels = null) |
55
|
|
|
{ |
56
|
1 |
|
$this->logger = $logger ?? new \Psr\Log\NullLogger(); |
57
|
|
|
$this->levels = $levels === null ? [] : array_map(function ($a) { |
58
|
|
|
return (string) $a; |
59
|
|
|
}, $levels); |
60
|
1 |
|
} |
61
|
|
|
|
62
|
|
|
/** |
63
|
|
|
* Logs an exception. |
64
|
|
|
* |
65
|
|
|
* If an exception isn't found in the `$levels` map, this class assumes a |
66
|
|
|
* level of `LogLevel::ERROR`. |
67
|
|
|
* |
68
|
|
|
* @param $e - The exception to log |
69
|
|
|
*/ |
70
|
1 |
|
public function log(\Exception $e) |
71
|
|
|
{ |
72
|
1 |
|
$out = LogLevel::ERROR; |
73
|
1 |
|
foreach ($this->levels as $class => $level) { |
74
|
|
|
if ($e instanceof $class) { |
75
|
|
|
$out = $level; |
76
|
|
|
break; |
77
|
|
|
} |
78
|
|
|
} |
79
|
1 |
|
$this->logger->log($out, $e->getMessage(), ['exception' => $e]); |
80
|
1 |
|
} |
81
|
|
|
} |
82
|
|
|
|