Track memory usage over time

Q I have recently rented an entry-level Linux server with a single SCSI disk and 1GB of RAM to host one of my websites. The server has crashed twice over the past two weeks and the hosting provider let me know that the server had to be rebooted because it had completely run out of memory. We were also told that we can investigate the contents of our sar log files for a history of memory use. We have since revised our scripts and hopefully the code has been made more memory-efficient. We've also created a 1GB swap file in addition to the existing 1GB swap partition as a precaution. Now we are thinking of writing some PHP scripts to process the sar logs to help us visually track memory usage over time and help us with capacity and upgrade planning. Is there a tool that does just that?

A MRTG (the Multi Router Traffic Grapher, ch/~oetiker/webtools/mrtg) is typically used to graph network bandwidth use but can be easily extended to plot other metrics Graphs are generated for the past day, week, month and year, making MRTG an excellent lightweight tool for visualising trends. To monitor memory and swap utilisation I use the following target in the MRTG configuration file:

Target[srvmem]: '/usr/local/sbin/'
Title[srvmem]: Mem and Swap
Mem and Swap Usage
ShortLegend[srvmem]: B
YLegend[srvmem]: Memory
LegendI[srvmem]: Swap
LegendO[srvmem]: Mem
Legend1[srvmem]: Swap
Legend2[srvmem]: Mem
Options[srvmem]: gauge,growright,
kMG[srvmem]: k,M,G,T,P,X
Colours[srvmem]: RED#bb0000,B

This calls the following script (/usr/local/sbin/ to get the amount of RAM and swap used:

/usr/bin/free -b | /bin/awk ' \
NR==2 { ramUsed = $3 } \
NR==4 { swapUsed = $3 } \
END { print swapUsed "\n"
ramUsed "\n0\n0" } '

Memory utilisation will be shown as a nice blue line and swap utilisation as a red line. There are many resources on the internet to help you set up MRTG, including It's easy to get carried away with MRTG, turning any possible aspect of a network into a graph. In such cases MRTG performance can be improved by using RRDtool as a logger and a third-party script as documented in the RRDtool Integration section of the MRTG documentation.

Follow us on or Twitter

Username:   Password: