← back to Handbag Auth Nextjs
scripts/devops/log-rotation.sh
78 lines
#!/bin/bash
#
# LUXVAULT Log Rotation Script
# Rotates and archives application logs
# Runs daily at 1am via cron
#
set -euo pipefail
PROJECT_DIR="/root/Projects/handbag-auth-nextjs"
LOG_DIR="$PROJECT_DIR/logs"
ARCHIVE_DIR="$LOG_DIR/archive"
DATA_DIR="$PROJECT_DIR/data/auction-history"
# Retention (days)
RETENTION_DAYS=14
ARCHIVE_RETENTION_DAYS=90
# Maximum log size (bytes) - 10MB
MAX_LOG_SIZE=10485760
TIMESTAMP=$(date +%Y%m%d_%H%M%S)
log() {
echo "[$(date +'%Y-%m-%d %H:%M:%S')] $*"
}
# Create directories
mkdir -p "$ARCHIVE_DIR"
log "Starting log rotation..."
# Function to rotate a log file
rotate_log() {
local log_file="$1"
local log_name=$(basename "$log_file")
if [ ! -f "$log_file" ]; then
return
fi
local file_size=$(stat -f%z "$log_file" 2>/dev/null || stat -c%s "$log_file")
# Only rotate if file exceeds max size
if [ "$file_size" -gt "$MAX_LOG_SIZE" ]; then
log "Rotating $log_name ($(echo "scale=2; $file_size / 1024 / 1024" | bc)MB)..."
# Compress and archive
gzip -c "$log_file" > "$ARCHIVE_DIR/${log_name}_${TIMESTAMP}.gz"
# Truncate original log file
> "$log_file"
log "✓ Rotated and archived $log_name"
fi
}
# Rotate application logs
rotate_log "$LOG_DIR/health-monitor.log"
rotate_log "$LOG_DIR/deployment.log"
rotate_log "$LOG_DIR/backup.log"
rotate_log "$LOG_DIR/alerts.log"
# Rotate data logs
rotate_log "$DATA_DIR/scraper.log"
rotate_log "$DATA_DIR/metrics.log"
# Clean up old archives
log "Cleaning up old archives (retention: ${ARCHIVE_RETENTION_DAYS} days)..."
find "$ARCHIVE_DIR" -name "*.gz" -mtime +$ARCHIVE_RETENTION_DAYS -delete
ARCHIVE_COUNT=$(find "$ARCHIVE_DIR" -name "*.gz" | wc -l)
ARCHIVE_SIZE=$(du -sh "$ARCHIVE_DIR" 2>/dev/null | cut -f1 || echo "0")
log "✓ Archive cleanup complete"
log "Archived logs: $ARCHIVE_COUNT files, $ARCHIVE_SIZE total"
log "Log rotation complete"