Tracking Fatal Errors in PHP
I recently implemented a really easy solution for tracking Fatal errors in PHP on my live sites. It is really helpful if you have a large codebase, or manage a large number of PHP sites. What I am doing first is to report all php errors to a log file, then watch the log file for Fatal errors then email them to myself.
So first step is to turn the error reporting to a log file in PHP (are you displaying yours to screen? cause on production servers you damn well shouldn’t!). To do this edit your php.ini file and find the line with:
error_log = /something;
now we will change this line to where we want out error log to go. Lets say we want our php errors put into a file called php_errors located in the /var/log folder. So our php.ini line would look like:
error_log = /var/log/php_errors
OK while you are in the php.ini file you might as well stop showing errors to the screen, to do that find the line:
display_errors = On
and change it to:
display_errors = Off
OK now we need to restart apache for that to take effect. After apache is restarted you should now start to see errors in the file /var/log/php_errors, and you should no longer be seeing PHP errors on your screen.
Now the next step of this is to report Fatal errors. For this I use SWATCH . I will let you figure out how to install it (pretty simple, make, make test, make install).
After SWATCH is installed lets make a config file for it to report on PHP Fatal errors. So I create a file called:
/etc/swatch/php_fatal_errors.conf
Swatch uses perl regular expressions to report on so to catch PHP fatal errors my config looks something like this:
# watch out for PHP Fatal Errors
watchfor /PHP Fatal error/
mail addresses=myemail\@address.com,subject=Fatal Error On Website
Notice that I escaped the @ symbol, this is because in perl the @ symbol is used for arrays. Anyway that is it. You can now start swatch by running:
swatch –config-file=/etc/swatch/php_fatal_errors.conf –tail-file=/var/log/php_errors &
This will start swatch in the background using the config file you have just created and will montior the PHP error log file we setup above. Now everytime there is a PHP fatal error on your site you will get an email. You may want to play around with the swatch config, specifically with the throttle directive as it will allow you to prevent yourself from getting overwhealmed with mass emails if you have a lot of errors.
Anyway that is it, a quick and easy way to monitor your live sites for PHP errors. While your code should be error free before you go live with it, you can’t always find all the errors, so this is an easy solution to tracking down those problems.
0 comments
Kick things off by filling out the form below.
Leave a Comment