Skip to content

Instantly share code, notes, and snippets.

@adyrcz
Created June 4, 2014 22:23
Show Gist options
  • Save adyrcz/6c7c7d8d782e2002c4c1 to your computer and use it in GitHub Desktop.
Save adyrcz/6c7c7d8d782e2002c4c1 to your computer and use it in GitHub Desktop.
rotatelog
#!/bin/bash
# rotates webserver log files
# Version 1.0
# Andy Dyrcz
# Get PATHS and SITENAME from control script name
# get absolute path to program folder
ctl=`readlink -f "$0"`
# get ServerRoot folder containing folders: bin/, conf/, log/, www/
SERVERROOT=${ctl%/*/*}
LOGDIR=$SERVERROOT/logs
HOST=`hostname -s`
DOMAIN=`hostname -d`
ENV=${DOMAIN%%.*}
WHOAMI=`whoami`
FILES="*.log"
# backup with timestamp, clear working file, compress after 3 days, delete after 10 days
DATE=`date +%Y%m%d.%H%M`
COMPRESS="+3"
REMOVE="+10"
ARCH=`uname`
if [ $ARCH == "Darwin" ]; then
XARGS_REPL_ARG="-I {}"
else
XARGS_REPL_ARG="-i"
fi
for log in $FILES
do
while read file
do
if [[ $file =~ $HOST ]]; then
# if file name contains host name already
cp $file $file.$ENV.$DATE
else
cp $file $file.$HOST.$ENV.$DATE
fi
> $file
done < <( find $LOGDIR/ -follow -type f -name $log )
echo "find $LOGDIR/ -follow -type f -mtime $COMPRESS -name \"$log.*\" -print | grep -v gz | xargs $XARGS_REPL_ARG gzip -f {} \;"
find $LOGDIR/ -follow -type f -mtime $COMPRESS -name "$log.*" -print | grep -v gz | xargs $XARGS_REPL_ARG gzip -f {} \;
find $LOGDIR/ -follow -type f -mtime $REMOVE -name "$log.*" -exec rm {} \;
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment