Logging fatal errors

suggest change

Some 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:

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents