How to log the memory consumption on Linux?

The following script prints time stamps and a header.

#!/bin/bash -e

echo "      date     time $(free -m | grep total | sed -E 's/^    (.*)/\1/g')"
while true; do
    echo "$(date '+%Y-%m-%d %H:%M:%S') $(free -m | grep Mem: | sed 's/Mem://g')"
    sleep 1
done

The output looks like this (tested on Ubuntu 15.04, 64-bit).

      date     time          total       used       free     shared    buffers     cached
2015-08-01 13:57:27          24002      13283      10718        522        693       2308
2015-08-01 13:57:28          24002      13321      10680        522        693       2308
2015-08-01 13:57:29          24002      13355      10646        522        693       2308
2015-08-01 13:57:30          24002      13353      10648        522        693       2308

A small script like

rm memory.log
while true; do free >> memory.log; sleep 1; done