36 lines
768 B
Bash
Executable File
36 lines
768 B
Bash
Executable File
#!/usr/bin/env bash
|
|
set -euo pipefail
|
|
|
|
LOG_FILE="${1:?log file required}"
|
|
MAX_BYTES="${2:-20971520}"
|
|
BACKUPS="${3:-5}"
|
|
|
|
mkdir -p "$(dirname "$LOG_FILE")"
|
|
touch "$LOG_FILE"
|
|
|
|
rotate_logs() {
|
|
local size
|
|
size="$(stat -c%s "$LOG_FILE" 2>/dev/null || echo 0)"
|
|
if [[ "$size" -lt "$MAX_BYTES" ]]; then
|
|
return
|
|
fi
|
|
|
|
local index
|
|
for ((index=BACKUPS; index>=1; index--)); do
|
|
if [[ -f "${LOG_FILE}.${index}" ]]; then
|
|
if [[ "$index" -eq "$BACKUPS" ]]; then
|
|
rm -f "${LOG_FILE}.${index}"
|
|
else
|
|
mv "${LOG_FILE}.${index}" "${LOG_FILE}.$((index + 1))"
|
|
fi
|
|
fi
|
|
done
|
|
mv "$LOG_FILE" "${LOG_FILE}.1"
|
|
: > "$LOG_FILE"
|
|
}
|
|
|
|
while IFS= read -r line || [[ -n "$line" ]]; do
|
|
rotate_logs
|
|
printf '%s\n' "$line" | tee -a "$LOG_FILE"
|
|
done
|