Monitor and log server load


« Back to overview

Here's a simple PHP script that you can execute that logs top and ps aux outputs in files every 30 seconds.
Useful if you know your server is offline at night and you want to know what happens and what services run.


<?php
/**
 * logs 'top' and 'ps -aux' server loads
 * 
 * (c) 2019 24hoursmedia - www.24hoursmedia.com
 */

$output_dir = '~/tmp-logs';
$interval = 30;         // interval between probing
$duration = 3600;       // seconds

exec('mkdir -p ' . $output_dir);
$expires = time() + $duration;
while (time() < $expires) {
        echo 'polling..' . PHP_EOL;     
        $basename = date('Ymd-His');

        $path = $output_dir . DIRECTORY_SEPARATOR . 'psaux-' . $basename . '.txt';
        $cmd = "ps aux > " . $path;

        exec($cmd);
        $path = $output_dir . DIRECTORY_SEPARATOR . 'top-' . $basename . '.txt';
        $cmd = "top -b -n 1 > " . $path;
        exec($cmd);
        echo 'sleeping..';
        sleep($interval);
}
echo 'done';