Maintaining Syslog Files on the Server
Problem
You want to automatically rotate and archive router logfiles on a Unix server.
Solution
The Bourne shell script in Example 18-1 automatically rotates router logfiles to ensure that these files don’t become too big and cumbersome to navigate. The script is intended to be invoked via a cron job on a daily basis, but you can also run it manually. By default, the script retains seven days worth of archived logfiles and compresses files older than two days. No arguments are required or expected.
Example 18-1. rotatelog.sh
#!/bin/sh
#
# rotatelog.sh -- a script to rotate logfiles and
# compress archived files
#
# Set behavior
SYSLOGPID=/etc/syslog.pid
LOGDIR=/var/log
LOG=rtrlog
DAYS=7
COMPRESS="/usr/bin/compress -f"
#
# Program body
[ -f $SYSLOGPID ] || echo "Syslog PID file doesn't exist"
if [ -d $LOGDIR ]; then
cd $LOGDIR
[ -f $LOG.1 ] && \Q$COMPRESS $LOG.1\Q && sleep 1
while [ $DAYS -gt 1 ]
do
LOW=\Qexpr $DAYS - 1\Q
[ -f $LOG.$LOW.Z ] && mv $LOG.$LOW.Z $LOG.$DAYS.Z
DAYS=$LOW
done
[ -f $LOG ] || echo "Log file $LOG doesn't exist"
[ -f $LOG ] && mv $LOG $LOG.1
touch $LOG
chmod 644 $LOG
sleep 10
kill -HUP \Qcat $SYSLOGPID\Q
#
else
echo "Log directory $LOGDIR is not valid"
fiDiscussion
If left unchecked, the router logfiles grow until your disk space runs out. This script is designed to rotate router logfiles on a daily basis to ensure they don’t grow too large.
This script will rotate logs on a daily basis and retain seven days worth of archived ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access