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
-
Write the logrotate configuration
Become
rootand add a file under/etc/logrotate.d/, which/etc/logrotate.confincludes.sudo -i vim /etc/logrotate.d/demoPress i and write the block, then Esc and
:wq./var/log/demo.log { size 1k rotate 2 compress missingok } -
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 -
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.gzhas taken its place. -
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.gzanddemo.log.2.gz. -
Confirm the oldest copy is discarded
rotate 2means 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* -
Clean up
rm -f /etc/logrotate.d/demo /var/log/demo.log*