This script is an advanced solution for automatically cleaning up old log files on your VPS. It includes error handling, logging, and customizable features to ensure efficient log management on Linux-based VPS systems.


#!/bin/bash

# Configuration
LOG_RETENTION_DAYS=30
LOG_DIRECTORIES=(
    "/var/log"
    "/var/log/nginx"
    "/var/log/apache2"
)
EXCLUDE_FILES=(
    "auth.log"
    "syslog"
)
LOGFILE="/var/log/log_cleanup_script.log"
ERROR_LOGFILE="/var/log/log_cleanup_errors.log"

# Function to log messages
log_message() {
    local message="$1"
    echo "$(date '+%Y-%m-%d %H:%M:%S') - $message" | tee -a "$LOGFILE"
}

# Function to log errors
log_error() {
    local message="$1"
    echo "$(date '+%Y-%m-%d %H:%M:%S') - ERROR: $message" | tee -a "$ERROR_LOGFILE"
}

# Function to clean up logs
cleanup_logs() {
    local dir=$1
    local files_deleted=0

    log_message "Cleaning logs in $dir older than $LOG_RETENTION_DAYS days..."

    for file in $(find "$dir" -type f \( -name "*.log" -o -name "*.gz" \) -mtime +$LOG_RETENTION_DAYS); do
        if [[ ! " ${EXCLUDE_FILES[@]} " =~ " $(basename "$file") " ]]; then
            rm -f "$file" && files_deleted=$((files_deleted + 1)) || log_error "Failed to delete $file"
        fi
    done

    log_message "$files_deleted files deleted from $dir"
}

# Start cleaning process
log_message "Starting advanced log cleanup..."

for dir in "${LOG_DIRECTORIES[@]}"; do
    if [ -d "$dir" ]; then
        cleanup_logs "$dir"
    else
        log_error "Directory $dir does not exist, skipping..."
    fi
done

log_message "Log cleanup completed successfully!"

# Optionally, add this script to cron for automatic execution:
# 0 0 * * * /path/to/this_script.sh

This enhanced script goes beyond basic log cleanup by adding several advanced features:

  • Error Handling: The script logs any errors that occur during the cleanup process to a separate error log file.
  • Exclusion List: Certain critical log files (like auth.log and syslog) can be excluded from deletion to prevent accidental removal.
  • Comprehensive Logging: All actions and deleted files are logged with timestamps, allowing for easy tracking and auditing.

By setting this script up on your VPS, you ensure your log management is both efficient and secure, helping to maintain optimal performance.