Logging fatal errors
suggest changeSome fatal errors still cannot be caught. Since PHP 7, Error can be caught with try/catch, and an uncaught one stops the script. register_shutdown_function runs at shutdown. The handler below logs E_ERROR only. It does not see warnings, and a parse error can happen before the handler is registered.
function fatalErrorHandler(): void
{
$error = error_get_last();
// No error means shutdown was normal. This example handles fatal errors only.
if ($error === null || $error['type'] !== E_ERROR) {
return;
}
$logFile = fopen('./app/logs/error.log', 'ab');
if ($logFile === false) {
return;
}
fprintf(
$logFile,
"[%s] %s: %s in %s:%d\n",
date('Y-m-d H:i:s'),
$error['type'],
$error['message'],
$error['file'],
$error['line'],
);
fclose($logFile);
}
register_shutdown_function('fatalErrorHandler');
Reference:
- http://php.net/manual/en/function.register-shutdown-function.php
- http://php.net/manual/en/function.error-get-last.php
- http://php.net/manual/en/errorfunc.constants.php
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents