0

How can I catch and log PHP fatal errors in CodeIgniter?

if (defined('ENVIRONMENT'))
{
    switch (ENVIRONMENT)
    {
        case 'development':
            error_reporting(E_ALL);
            ini_set('display_errors', '1');
        break;

        case 'testing':
        case 'production':
            error_reporting(0);
        break;

        default:
            exit('The application environment is not set correctly.');
    }
}

When environment is set to production and there's a fatal error, I just get a white screen. If the environment is set to development, the error gets displayed in the browser but it doesn't get logged. I have error logging enabled but it only catches PHP notices and warnings.

4
Contributors
5
Replies
40
Views
3 Years
Discussion Span
Last Post by Dani
1

PHP isn't designed to degrade nicely for fatal errors (i.e. parse errors). I did some research and got the following to work. Hopefully it can help others:

register_shutdown_function('_foo');

function _foo()
{
    if ($error = error_get_last())
    {
        $foo = date('Y-m-d H:i:s') . ' --> ' . $error['file'] . ' --> ' . $error['message'] . ' ' . $error['line'];
        file_put_contents('./logs/fatal_errors.php', "$foo\n", FILE_APPEND);
    }
}
0

I have error logging enabled but it only catches PHP notices and warnings.

Check your INI file, mine is set to E_ALL and the log shows them.

1

Thanks Dani for posting your solution :)

I found the same approach but with the use of hooks to register this function on "pre_system" here

0

Check your INI file, mine is set to E_ALL and the log shows them.

That's the same as line 6 in my initial code snippet. The problem is, it doesn't catch PHP fatal errors that halt script execution.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.