Exercise

Rotating a Log File by Size Exercise

Task

Rotate a log file when it outgrows 1 KB, compress the old copies, and keep only the two most recent.

Host
servera
Log file
/var/log/demo.log
Rotate when
the file grows past 1k
Keep
2 compressed copies
  1. Write the logrotate configuration

    Become root and add a file under /etc/logrotate.d/, which /etc/logrotate.conf includes.

    sudo -i
    vim /etc/logrotate.d/demo

    Press i and write the block, then Esc and :wq.

    /var/log/demo.log {
        size 1k
        rotate 2
        compress
        missingok
    }
  2. Fill the file past the threshold

    for i in {1..100}; do echo "Log entry line $i" >> /var/log/demo.log; done
    ls -lh /var/log/demo.log
  3. Rotate it by hand

    Rather than waiting for logrotate.timer, force a run now.

    logrotate --force /etc/logrotate.d/demo
    ls -lh /var/log/demo.log*

    The original is gone and demo.log.1.gz has taken its place.

  4. Fill and rotate again

    for i in {1..100}; do echo "Log entry line $i" >> /var/log/demo.log; done
    logrotate --force /etc/logrotate.d/demo
    ls -lh /var/log/demo.log*

    Now there are two: demo.log.1.gz and demo.log.2.gz.

  5. Confirm the oldest copy is discarded

    rotate 2 means two old copies, so a third rotation has to drop one.

    for i in {1..100}; do echo "Log entry line $i" >> /var/log/demo.log; done
    logrotate --force /etc/logrotate.d/demo
    ls -lh /var/log/demo.log*
  6. Clean up

    rm -f /etc/logrotate.d/demo /var/log/demo.log*