Posted on

Counting the most common PHP error logs

Keeping an eye on your error logs is something that most developers neglect. Server administrators, on the other hand, tend to look out for these minor details, as they’ll keep your website secure and ensure there are no warnings, notices or even fatal errors that you may have missed during development.

You can check to where your error log files are piping their information by checking a phpinfo() file (just a php file with the following code inside (be sure to start the file with a php open tag):


Or you can check via the command line using this command:

php -i | grep error_log

which simply shows the php information and configuration, piping with grep and finding the string ‘error_log’. It will then return where your error log files are. This will either be at an absolute path, starting with a forward slash (/var/log/php5-fpm.log), or, it will be a relative file such as ‘error_log’. This means the error log will be at the relative path of the executed script that produced the error.

Once you have found the path for your error log, you can run a simple command (it’s simple once we break it down) that will count your errors so you can go ahead and remove the most common errors that are clogging up your php error log:

cat /var/log/php-errors.log | sort | uniq -c | sort -rn | head

Let’s break that down. The cat command simply outputs the content of the file you have defined. You’ll notice everything after that uses a pipe (|) to layer on other commands to that output. The sort command – yes, you guessed it – sorts the data numerically and alphabetically. The uniq command removes any duplicates, line by line (makes each line unique) and the -c flag puts a count at the beginning of each line showing how many matches it found. The sort command sorts the data again (after identifying the duplicates) with the -r (which reverses the order, you’ll see why in the last command) and -n flag. Finally, the head command returns the last 10 lines (10 lines by default – you can change this number using the -n, just check the manual).

If your errors (like mine) are relative, you can create a global file using this command:

cat /home/*/public_html/error_log > /var/log/php-errors.log

After starting a new job, I had to take over a few servers which kept going down. After finding out the disk space was full almost every week which caused the server to go ka-boom, I found the PHP FPM error log was over 15GB is size! Amazing, huh? About 40 sites had been developed with no debugging turned on locally so all of these errors had been adding up. Since these sites had quite a lot of traffic, we found ourselves having to truncate the error log almost ever week to free up disk space until IĀ could get round to fixing the most common errors.