Last Updated: February 25, 2016
·
6.45K
· saml

Log Memory Usage per second or minute on Linux

To log memory usage every second:

sar -r 1

To log memory usage every minute:

sar -r 60

Running sar -r 1 will give the following output to "standard output" (which is your terminal when you use the command from the terminal):

[samuel ~]$ sar -r 1
<snip some computer info>

10:54:08    kbmemfree kbmemused  %memused kbbuffers  kbcached  kbcommit   %commit  kbactive   kbinact
10:54:09      1423000   6595688     82,25    542304   1913592   8017084     49,34   4009672   1572904
10:54:10      1423080   6595608     82,25    542304   1913588   8017084     49,34   4009980   1572904
10:54:11      1422580   6596108     82,26    542304   1913588   8017084     49,34   4009984   1572904
10:54:12      1422396   6596292     82,26    542304   1913588   8017084     49,34   4010160   1572912
10:54:13      1422680   6596008     82,26    542328   1913556   8017084     49,34   4010308   1572888
10:54:14      1428440   6590248     82,19    542340   1907840   8011624     49,31   4010468   1567212
10:54:15      1428076   6590612     82,19    542340   1907836   8012644     49,32   4010520   1567180
10:54:16      1428080   6590608     82,19    542340   1907836   8012644     49,32   4010632   1567180

(Unfortunately the window here on coderwall is a bitt too narrow, so the lines are broken. On the terminal it looks much nicer!)

I find myself using especially the 4:th column, %memused, to quickly have a glance at if I'm about to outrun all of my RAM.

If you want to log the output to a file, you can of course either pipe it directly to a file:

sar -r 1 > somefile.log

... or run it through the tee command, so you can see the output at the same time:

sar -r 1 | tee somefile.log

The sar (System Activity Report) tool is available on Ubuntu via the sysstat package (So, to install on Ubuntu, do: sudo apt-get install sysstat).

3 Responses
Add your response

Where are the logs stored? What do they look like? Do you find them useful?

over 1 year ago ·

@adevore3, the command just outputs to stdout, so to do logging, you will have to either pipe directly to a file. Just updated the tip with some more info about that. Thanks for the constructive feedback!

over 1 year ago ·

You can also enable sar by having it run in cron every 60 seconds if you need to enable logging every minute.
This is one way under ubuntu:
create a file under /etc/cron.d/sysstat

vi /etc/cron.d/sysstat, add the following line:

*/1 * * * * root /usr/local/lib/sa/sa1 1 1

Then run sar and you will see the entries recorded at the specified interval.

over 1 year ago ·