Skip to content

Instantly share code, notes, and snippets.

@jalogut
Last active April 10, 2017 09:27
Show Gist options
  • Save jalogut/3f4d4be385a00aa2e4d45481a7f98521 to your computer and use it in GitHub Desktop.
Save jalogut/3f4d4be385a00aa2e4d45481a7f98521 to your computer and use it in GitHub Desktop.
logrotate
#!/bin/bash
# Run this script whenever you need to update the logrotate configuration for your website.
# You can do that in 3 ways:
# a) Execute this script Manually
# b) Schedule it on a cronjob
# c) Execute it every time before the rotation takes place. Call this script on first line of your logrotate "/etc/cron.daily/logrotate"
# -e = stop if something fails
# -u = fail if you try to use an unset variable.
set -eu
clearConfigFile () {
echo "
# FILE automatically generated
" > "${CONFIG_FILENAME}"
}
getLogFolderProperties () {
USER=$(stat -c "%U" "${ORIG_DIR}")
GROUP=$(stat -c "%G" "${ORIG_DIR}")
PERMISSIONS=$(stat -c "%a" "${ORIG_DIR}")
}
createOldDir () {
getLogFolderProperties
if [ ! -d "${OLD_DIR}" ]; then
mkdir -p "${OLD_DIR}"
chown -R "${USER}":"${GROUP}" "${LOG_DIR}"/"${DEST_SUBDIR}"
chmod -R "${PERMISSIONS}" "${LOG_DIR}"/"${DEST_SUBDIR}"
fi
}
addLogConfig () {
echo "${ORIG_DIR}/*.log {
su root root
olddir ${OLD_DIR}
weekly
rotate 12
missingok
compress
delaycompress
notifempty
dateext
dateformat -%Y-%m-%d
}
" >> "${CONFIG_FILENAME}"
}
createConfigFile () {
clearConfigFile
LOG_DIRS=$(find "${BASE_DIR}" -type d -name log -not -iwholename "*vendor*" -not -iwholename "*cache*")
for LOG_DIR in ${LOG_DIRS}
do
LOG_SUBDIRS=$(find "${LOG_DIR}" -type d -not -iwholename "*${DEST_SUBDIR}*")
for LOG_SUBDIR in ${LOG_SUBDIRS}
do
LOG_RELATIVE_DIR=${LOG_SUBDIR:${#LOG_DIR}}
ORIG_DIR=${LOG_SUBDIR}
OLD_DIR=${LOG_DIR}/${DEST_SUBDIR}${LOG_RELATIVE_DIR}
createOldDir
addLogConfig
done
done
}
# Script Start
BASE_DIR=/home
DEST_SUBDIR=logs_rotated
CONFIG_FILENAME=/etc/logrotate.d/webspaces
createConfigFile
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment