Wednesday, April 25, 2012

Logging fatal PHP errors

If you turned off the display_errors setting in your php.ini in production (as you should), then when your code dies with a fatal error, you can't see the message anywhere. It would be better to log these errors to the Apache error log (this is true even if you didn't disable display_errors, for debugging errors that other users might report.) PHP has a log_errors directive in php.ini, but it doesn't seem to log anything for me. Instead, I used register_shutdown_function() to make PHP log the errors:

register_shutdown_function(function() {
  $error = error_get_last();
  if($error !== NULL) {
  error_log('PHP Fatal: file:' . $error['file'] . ' line:' . $error['line'] .
            ' type:' . $error['type'] . ' message:' . $error['message']);
  }
});

This causes PHP to log the error on shutdown.

No comments: