Quick way to grab and use server load average data

One day I needed to grab just the 3 server load average numbers (more on server load averages here) to log them in a database along with few other parameters for some quick analyses. I queried Google for it, but did not find anything that would work for me in first 5 minutes, so I decided to write a quick load number grabber of my own in PHP and using scheduling tasks with cron.

Here are the steps to set it up:

1. Create a plain file where to store the top command information including load numbers using cron for Linux :

*/5     *     *     *     *     top -b | head | grep -2 “load average” >> /var/log/loadaverage.log

If you add the code above to your cron jobs (usually the location for cron jobs file is something like in /etc/crontab), it would store the top command results in the named file every 5 minutes. This way you will not need to allow PHP to access the command-line.

2. Create this script to parse contents of the file mentioned in Step 1, I called the file parse_log.php:

<?php

$filename = ‘/var/log/loadaverage.log’; //The path to file of the “top” commands you created in Step 1 above
$file = file_get_contents($filename);
$chunks = explode(“si\n”, $file);

for($i=0;$i<=count($chunks);$i++) {

$time_start_pos = strpos($chunks[$i], ‘top – ‘);
$chunks[$i] = substr($chunks[$i], $time_start_pos);

if (($time_start_pos = strpos($chunks[$i], ‘ ‘)) === false) break;

$chunks[$i] = substr($chunks[$i], $time_start_pos + strlen(‘up ‘));
$time = substr($chunks[$i], 0, strpos($chunks[$i], ‘ ‘));
$la_start_pos = strpos($chunks[$i], ‘average:’);
$chunks[$i] = substr($chunks[$i], $la_start_pos);

if (($la_start_pos = strpos($chunks[$i], ‘ ‘)) === false) break;

$chunks[$i] = substr($chunks[$i], $la_start_pos + strlen(‘ ‘));
$la = substr($chunks[$i], 0, strpos($chunks[$i], ‘Tasks’));

list($l1, $l2, $l3) = explode(“, “, $la);

}

?>

3. Now you can use the $l1 (for 1-minute load average), $l2 (for 5-minute load average) and $l3 (for 15-minute load average) as parameters in your script for whatever reason – for storing the numbers in database, for creating an e-mail alert when any of the load average numbers go above some limit, or anything you wish. A quick example for e-mail alert when the 1-minute load average exceeds 20 for adding to the code above:

if($l1>20) mail(“user@example.com”, “Server load alert”, “Current server loads: “.$l1.”, “.$l2.”, “.$l3);

4. Schedule the parse_log.php script to parse the contents of the “top” command results using cron (every 5 minutes in example):

*/5     *     *     *     *     /usr/local/bin/php /var/log/parse_log.php

Please note that all the paths (marked in grey) depend on your server setup – you should find them out yourself. I know the parsing code in the example is not the “best practice” and plainly – it is ugly, but I needed a quick solution and it works fine. Hopefully it will work for any of you.

Leave a Reply