-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathErrorHandler.php
More file actions
executable file
·122 lines (104 loc) · 2.88 KB
/
ErrorHandler.php
File metadata and controls
executable file
·122 lines (104 loc) · 2.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
<?php
namespace BaseModule\Logger;
use Zend\Log\Logger;
/**
* Simple Logger to log Exceptions
*
* @copyright Felix Buchheim
* @author Felix Buchheim <hanibal4nothing@gmail.com>
*/
class ErrorHandler
{
/**
* Logger for exceptions
*
* @var Logger
*/
protected $exceptionLogger;
/**
* Logger for fatalErrors
*
* @var Logger
*/
protected $fatalErrorLogger;
/**
* Multiple logger for sysLog
*
* @var LoggerCollection
*/
protected $sysLogger;
/**
* ErrorHandler constructor.
*
* @param Logger|null $oExceptionLogger
* @param Logger|null $oFatalErrorLogger
* @param LoggerCollection|null $oSysLogger
*/
public function __construct(
Logger $oExceptionLogger = null,
Logger $oFatalErrorLogger = null,
LoggerCollection $oSysLogger = null
) {
$this->exceptionLogger = $oExceptionLogger;
$this->fatalErrorLogger = $oFatalErrorLogger;
$this->sysLogger = $oSysLogger;
}
/**
* Log a single exception
*
* @param \Exception $e
*
* @return $this
*/
public function log(\Exception $e)
{
if (false === isset($this->exceptionLogger)) {
throw new \RuntimeException('ExceptionLogger is not set');
}
$sTrace = $e->getTraceAsString();
$iCounter = 1;
$aMessages = array();
do {
$aMessages[] = ($iCounter++) . ": \n" . $e->getMessage();
} while ($e = $e->getPrevious());
$sLog = 'Exception ' . implode(PHP_EOL, $aMessages);
$sLog .= " \nTrace: \n" . $sTrace;
$this->exceptionLogger->err($sLog);
return $this;
}
/**
* Register different logger as errorHandler
*
* @return $this
*/
public function registerAsErrorHandler()
{
if (false === isset($this->sysLogger)) {
throw new \RuntimeException('Syslogger are not set');
}
foreach ($this->sysLogger as $iPriority => $oLogger) {
set_error_handler(function ($iCode, $sMessage, $sFile, $iLine) use ($oLogger) {
$sType = Logger::$errorPriorityMap[$iCode];
/* @var \BaseModule\Logger\Logger $oLogger */
$oLogger->log($sType, $sMessage . PHP_EOL, [
'file' => $sFile,
'line' => $iLine,
]);
}, $iPriority);
}
return $this;
}
/**
* Register the fatalErrorLogger zu log fatalErrors
*
* @return $this
*/
public function registerFatalErrorHandler()
{
if (false === isset($this->fatalErrorLogger)) {
throw new \RuntimeException('FatalErrorLogger are not set');
}
Logger::registerFatalErrorShutdownFunction($this->fatalErrorLogger);
return $this;
}
}