1<?php declare(strict_types=1);
2
3/*
4 * This file is part of the Monolog package.
5 *
6 * (c) Jordi Boggiano <j.boggiano@seld.be>
7 *
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
10 */
11
12namespace Monolog;
13
14use Psr\Log\LoggerInterface;
15use Psr\Log\LogLevel;
16
17/**
18 * Monolog error handler
19 *
20 * A facility to enable logging of runtime errors, exceptions and fatal errors.
21 *
22 * Quick setup: <code>ErrorHandler::register($logger);</code>
23 *
24 * @author Jordi Boggiano <j.boggiano@seld.be>
25 */
26class ErrorHandler
27{
28    private $logger;
29
30    private $previousExceptionHandler;
31    private $uncaughtExceptionLevelMap;
32
33    private $previousErrorHandler;
34    private $errorLevelMap;
35    private $handleOnlyReportedErrors;
36
37    private $hasFatalErrorHandler;
38    private $fatalLevel;
39    private $reservedMemory;
40    private $lastFatalTrace;
41    private static $fatalErrors = [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR, E_USER_ERROR];
42
43    public function __construct(LoggerInterface $logger)
44    {
45        $this->logger = $logger;
46    }
47
48    /**
49     * Registers a new ErrorHandler for a given Logger
50     *
51     * By default it will handle errors, exceptions and fatal errors
52     *
53     * @param  LoggerInterface   $logger
54     * @param  array|false       $errorLevelMap     an array of E_* constant to LogLevel::* constant mapping, or false to disable error handling
55     * @param  array|false       $exceptionLevelMap an array of class name to LogLevel::* constant mapping, or false to disable exception handling
56     * @param  string|null|false $fatalLevel        a LogLevel::* constant, null to use the default LogLevel::ALERT or false to disable fatal error handling
57     * @return ErrorHandler
58     */
59    public static function register(LoggerInterface $logger, $errorLevelMap = [], $exceptionLevelMap = [], $fatalLevel = null): self
60    {
61        /** @phpstan-ignore-next-line */
62        $handler = new static($logger);
63        if ($errorLevelMap !== false) {
64            $handler->registerErrorHandler($errorLevelMap);
65        }
66        if ($exceptionLevelMap !== false) {
67            $handler->registerExceptionHandler($exceptionLevelMap);
68        }
69        if ($fatalLevel !== false) {
70            $handler->registerFatalHandler($fatalLevel);
71        }
72
73        return $handler;
74    }
75
76    public function registerExceptionHandler($levelMap = [], $callPrevious = true): self
77    {
78        $prev = set_exception_handler(function (\Throwable $e): void {
79            $this->handleException($e);
80        });
81        $this->uncaughtExceptionLevelMap = $levelMap;
82        foreach ($this->defaultExceptionLevelMap() as $class => $level) {
83            if (!isset($this->uncaughtExceptionLevelMap[$class])) {
84                $this->uncaughtExceptionLevelMap[$class] = $level;
85            }
86        }
87        if ($callPrevious && $prev) {
88            $this->previousExceptionHandler = $prev;
89        }
90
91        return $this;
92    }
93
94    public function registerErrorHandler(array $levelMap = [], $callPrevious = true, $errorTypes = -1, $handleOnlyReportedErrors = true): self
95    {
96        $prev = set_error_handler([$this, 'handleError'], $errorTypes);
97        $this->errorLevelMap = array_replace($this->defaultErrorLevelMap(), $levelMap);
98        if ($callPrevious) {
99            $this->previousErrorHandler = $prev ?: true;
100        }
101
102        $this->handleOnlyReportedErrors = $handleOnlyReportedErrors;
103
104        return $this;
105    }
106
107    /**
108     * @param string|null $level              a LogLevel::* constant, null to use the default LogLevel::ALERT or false to disable fatal error handling
109     * @param int         $reservedMemorySize Amount of KBs to reserve in memory so that it can be freed when handling fatal errors giving Monolog some room in memory to get its job done
110     */
111    public function registerFatalHandler($level = null, int $reservedMemorySize = 20): self
112    {
113        register_shutdown_function([$this, 'handleFatalError']);
114
115        $this->reservedMemory = str_repeat(' ', 1024 * $reservedMemorySize);
116        $this->fatalLevel = $level;
117        $this->hasFatalErrorHandler = true;
118
119        return $this;
120    }
121
122    protected function defaultExceptionLevelMap(): array
123    {
124        return [
125            'ParseError' => LogLevel::CRITICAL,
126            'Throwable' => LogLevel::ERROR,
127        ];
128    }
129
130    protected function defaultErrorLevelMap(): array
131    {
132        return [
133            E_ERROR             => LogLevel::CRITICAL,
134            E_WARNING           => LogLevel::WARNING,
135            E_PARSE             => LogLevel::ALERT,
136            E_NOTICE            => LogLevel::NOTICE,
137            E_CORE_ERROR        => LogLevel::CRITICAL,
138            E_CORE_WARNING      => LogLevel::WARNING,
139            E_COMPILE_ERROR     => LogLevel::ALERT,
140            E_COMPILE_WARNING   => LogLevel::WARNING,
141            E_USER_ERROR        => LogLevel::ERROR,
142            E_USER_WARNING      => LogLevel::WARNING,
143            E_USER_NOTICE       => LogLevel::NOTICE,
144            E_STRICT            => LogLevel::NOTICE,
145            E_RECOVERABLE_ERROR => LogLevel::ERROR,
146            E_DEPRECATED        => LogLevel::NOTICE,
147            E_USER_DEPRECATED   => LogLevel::NOTICE,
148        ];
149    }
150
151    private function handleException(\Throwable $e)
152    {
153        $level = LogLevel::ERROR;
154        foreach ($this->uncaughtExceptionLevelMap as $class => $candidate) {
155            if ($e instanceof $class) {
156                $level = $candidate;
157                break;
158            }
159        }
160
161        $this->logger->log(
162            $level,
163            sprintf('Uncaught Exception %s: "%s" at %s line %s', Utils::getClass($e), $e->getMessage(), $e->getFile(), $e->getLine()),
164            ['exception' => $e]
165        );
166
167        if ($this->previousExceptionHandler) {
168            ($this->previousExceptionHandler)($e);
169        }
170
171        if (!headers_sent() && !ini_get('display_errors')) {
172            http_response_code(500);
173        }
174
175        exit(255);
176    }
177
178    /**
179     * @private
180     */
181    public function handleError($code, $message, $file = '', $line = 0, $context = [])
182    {
183        if ($this->handleOnlyReportedErrors && !(error_reporting() & $code)) {
184            return;
185        }
186
187        // fatal error codes are ignored if a fatal error handler is present as well to avoid duplicate log entries
188        if (!$this->hasFatalErrorHandler || !in_array($code, self::$fatalErrors, true)) {
189            $level = $this->errorLevelMap[$code] ?? LogLevel::CRITICAL;
190            $this->logger->log($level, self::codeToString($code).': '.$message, ['code' => $code, 'message' => $message, 'file' => $file, 'line' => $line]);
191        } else {
192            $trace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS);
193            array_shift($trace); // Exclude handleError from trace
194            $this->lastFatalTrace = $trace;
195        }
196
197        if ($this->previousErrorHandler === true) {
198            return false;
199        } elseif ($this->previousErrorHandler) {
200            return ($this->previousErrorHandler)($code, $message, $file, $line, $context);
201        }
202
203        return true;
204    }
205
206    /**
207     * @private
208     */
209    public function handleFatalError()
210    {
211        $this->reservedMemory = '';
212
213        $lastError = error_get_last();
214        if ($lastError && in_array($lastError['type'], self::$fatalErrors, true)) {
215            $this->logger->log(
216                $this->fatalLevel === null ? LogLevel::ALERT : $this->fatalLevel,
217                'Fatal Error ('.self::codeToString($lastError['type']).'): '.$lastError['message'],
218                ['code' => $lastError['type'], 'message' => $lastError['message'], 'file' => $lastError['file'], 'line' => $lastError['line'], 'trace' => $this->lastFatalTrace]
219            );
220
221            if ($this->logger instanceof Logger) {
222                foreach ($this->logger->getHandlers() as $handler) {
223                    $handler->close();
224                }
225            }
226        }
227    }
228
229    private static function codeToString($code): string
230    {
231        switch ($code) {
232            case E_ERROR:
233                return 'E_ERROR';
234            case E_WARNING:
235                return 'E_WARNING';
236            case E_PARSE:
237                return 'E_PARSE';
238            case E_NOTICE:
239                return 'E_NOTICE';
240            case E_CORE_ERROR:
241                return 'E_CORE_ERROR';
242            case E_CORE_WARNING:
243                return 'E_CORE_WARNING';
244            case E_COMPILE_ERROR:
245                return 'E_COMPILE_ERROR';
246            case E_COMPILE_WARNING:
247                return 'E_COMPILE_WARNING';
248            case E_USER_ERROR:
249                return 'E_USER_ERROR';
250            case E_USER_WARNING:
251                return 'E_USER_WARNING';
252            case E_USER_NOTICE:
253                return 'E_USER_NOTICE';
254            case E_STRICT:
255                return 'E_STRICT';
256            case E_RECOVERABLE_ERROR:
257                return 'E_RECOVERABLE_ERROR';
258            case E_DEPRECATED:
259                return 'E_DEPRECATED';
260            case E_USER_DEPRECATED:
261                return 'E_USER_DEPRECATED';
262        }
263
264        return 'Unknown PHP error';
265    }
266}
267