bash
DevOps
Log Rotation Script
Flexible log rotation script with compression, size-based rotation, and configurable retention policies.
Apex Logic
0 copies
bash
#!/bin/bash
# Log Rotation Script with compression and retention
set -euo pipefail
LOG_DIR="${1:-/var/log/myapp}"
MAX_SIZE_MB="${2:-50}"
KEEP_DAYS="${3:-30}"
COMPRESS="${4:-true}"
log() { echo "[$(date '+%Y-%m-%d %H:%M:%S')] $1"; }
log "=== Log Rotation: $LOG_DIR ==="
log "Max size: ${MAX_SIZE_MB}MB | Retain: ${KEEP_DAYS} days | Compress: $COMPRESS"
# Find log files exceeding max size
MAX_SIZE_BYTES=$((MAX_SIZE_MB * 1024 * 1024))
find "$LOG_DIR" -name "*.log" -type f | while read -r logfile; do
FILE_SIZE=$(stat -f%z "$logfile" 2>/dev/null || stat -c%s "$logfile" 2>/dev/null)
if [ "$FILE_SIZE" -gt "$MAX_SIZE_BYTES" ]; then
ROTATED="${logfile}.$(date +%Y%m%d_%H%M%S)"
cp "$logfile" "$ROTATED"
truncate -s 0 "$logfile"
log "Rotated: $(basename $logfile) ($(numfmt --to=iec $FILE_SIZE))"
if [ "$COMPRESS" = "true" ]; then
gzip "$ROTATED"
log "Compressed: $(basename $ROTATED).gz"
fi
fi
done
# Remove old rotated logs
OLD_COUNT=$(find "$LOG_DIR" \( -name "*.log.*.gz" -o -name "*.log.[0-9]*" \) -mtime +$KEEP_DAYS | wc -l)
if [ "$OLD_COUNT" -gt 0 ]; then
find "$LOG_DIR" \( -name "*.log.*.gz" -o -name "*.log.[0-9]*" \) -mtime +$KEEP_DAYS -delete
log "Removed $OLD_COUNT old log files"
fi
# Summary
TOTAL_SIZE=$(du -sh "$LOG_DIR" | cut -f1)
FILE_COUNT=$(find "$LOG_DIR" -type f | wc -l)
log "Directory: $TOTAL_SIZE total, $FILE_COUNT files"
log "=== Rotation complete ==="