Manually rotate and gzip squid logs

Squid logs can be rotated using newsyslog, logrotate, or squid -k rotate. If using squid, they will not be compressed and those logs can get quite big. Wrote a small script that renames the just closed log using yesterday’s date and gzips it. This way there will be a month worth of logs around. Kinda, doesn’t care for how many days a month has.

# rotate the logs using squid
# remove store.log.0 since it's too big and mostly for debugging
# then move every *.log.0 file (the log that just got rotated)
# *.log.day-of-month and gzip it

# edit the path to squid and to logs dir

/usr/local/sbin/squid -k rotate

sleep 600

cd /var/squid/logs/
rm store.log.0

for i in *.log.0
do
    j=$(echo $i | sed s/0$//)
    YESTERDAY=`date -r $((\`date +%s\`-86400)) +%d`
    mv $i $j$YESTERDAY
    rm -f $j$YESTERDAY.gz
    gzip -9f $j$YESTERDAY
done

Runs every night at midnight and it was written for OpenBSD. This is relevant for line 18, which obtains yesterday’s date by converting current date to seconds since epoch, subtracting 24 hours and converting back. On FreeBSD there’s date -v-1d +%d for that, using GNU (Linux) date, it would be date --date="yesterday" +%d.

Because squid -k rotate takes a while to complete the rotation, but exits right away, the script just sleeps for 10 minutes in order to allow the process to complete. The proper way would probably be to periodically check if it’s done, but it’s good enough for me.