Last active
November 9, 2015 10:17
-
-
Save stemid/f605151fcd358be61e33 to your computer and use it in GitHub Desktop.
Demonstration of compressing and purging old logs
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
# Compress and purge old logs | |
# by Stefan Midjich | |
# Compress logs older than X months | |
compressAge=2 | |
# Purge logs older than X months | |
purgeAge=3 | |
# Where are logs? | |
logBase=/var/log/remote | |
# Make no edits below this line if you want to live. | |
compressTime=$(date -d "$compressAge months ago" +%s) | |
purgeTime=$(date -d "$purgeAge months ago" +%s) | |
compressMonth=$(date -d @"$compressTime" +%m) | |
purgeMonth=$(date -d @"$purgeTime" +%m) | |
# Recursively compress all *.log files in $dir | |
compress () { | |
dir=$1 | |
shift | |
if [ ! -d "$dir" ]; then | |
return 1 | |
fi | |
for file in $dir/*; do | |
if [ -f "$file" ]; then | |
xz -z "$file" | |
fi | |
if [ -d "$file" ]; then | |
compress "$file" | |
fi | |
done | |
} | |
# Reset year to same year as compressMonth | |
year=$(date -d @"$compressTime" +%Y) | |
# Check input | |
if [ -z "$logBase" -o -z "$year" -o -z "$purgeMonth" -o -z "$compressMonth" ]; then | |
logger -p local0.error -t purge_remote_logs "Must configure script, see comments, exiting..." | |
exit 1 | |
fi | |
# Compress old logs | |
for dir in $logBase/$year/??; do | |
if [ "$(basename $dir)" -eq $compressMonth ]; then | |
logger -p local0.debug -t purge_remote_logs "Reached $dir, bailing on compress" | |
break | |
fi | |
logger -p local0.info -t purge_remote_logs "Compressing logs in $dir" && compress "$dir" &>/dev/null | |
# Reset permissions | |
find "$dir" -type f -exec chmod 0640 {} \; | |
done | |
# Reset year before purging old logs | |
year=$(date -d @"$purgeTime" +%Y) | |
# Purge old logs | |
if [ -d "$logBase/$year/$purgeMonth" ]; then | |
logger -p local0.info -t purge_remote_logs "Removing $logBase/$year/$purgeMonth" && rm -rf "$logBase/$year/$purgeMonth" | |
fi |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment