coderholic

PHP Error Log Mail Script

With the configuration option "log_errors" PHP will log all errors to the Apache error log file, allowing you to see all of the errors that have occurred while people have been using your site. Given the snippet of code below:

<?php
    // Ensure logging is enabled. Ideally this will be set in php.ini
    ini_set('log_errors', 'On');
    // Call a non-existant function to generate an error
    doesNotExist();
?>

You'll see something like the following entry in the error log, which includes a description of the problem and the file and line number of where the problem occurred:

[Tue May 26 19:54:53 2009] [error] [client 127.0.0.1] PHP Fatal error: Call to undefined function doesNotExist() in /var/www/index.php on line 6

I've written a small bash script to mail me all of the PHP errors that it finds in the log. The results are sorted and piped through the "uniq" command to remove any duplicate errors. I've set it up to run as a cron task once a day, so if there are ever any problems it isn't long before I know about them. The code is below:

#!/bin/bash
# Mail out PHP errors that are in the apache error log.
# Note PHP's log_errors must be turned on
# Ben Dowling - www.coderholic.com

errorLog=/var/log/apache2/error.log # Error log location
email=you-email-address@example.com # Send report here

# Pull out the lines that mention PHP, and use AWK to get the column we're interested in
errors=$(cat $errorLog | grep PHP | awk -F'] ' '{print $4}')
# Remove referer information, sort, and remove duplicate entries
errors=$(echo "$errors" | awk -F', referer' '{print $1}' | sort | uniq)
# Check that we actually have some errors
if [ -n "$errors" ] 
then
    echo "$errors" | mail "$email" -s "PHP Errors"
fi

If you need to it should be quite easy to modify the script for a slightly different use, such as printing out all the fatal PHP errors that are in the log.

Hope you find it useful!

Posted on 26 May 2009
If you enjoyed reading this post you might want to follow @coderholic on twitter or browse though the full blog archive.