If your VPS or Dedicated Server is constantly running out of memory or its CPU usage is spiking with no apparent reason, then it’s time to track the process, which stands behind all that. Instead of constantly watching the server processes for hours, trying to see that elusive process, there is a much easier way – to set up an automatic logging script and review the results.
The following sh script can be run every minute through cron to allow you to track considerable data in the minutes leading up to a crash or a server freeze. The data is saved to a logging directory, using the number for the minute as the file name. In this script setup below, it will create 60 files, which are refreshed with new data every 60 minutes:
#!/bin/sh
TERM=vt100
export TERM
time=$(date)
min=${time:14:2}
top -b -n 1 > /home/my-home/log/$min
ps aux >> /home/my-home/log/$min
exit 0
Note that running the above script without any idea of logrotate can load up your server’s disk space in no time. The best solution would be to set the script to save data to /tmp so that if this partition overfills you can easily clean it up.