BASH

Automate Log Archiving and Cleanup

Create a Bash script to automatically rotate, compress, and clean up old log files, managing disk space and maintaining server health efficiently.

#!/bin/bash
LOG_DIR="/var/log/mywebapp"
ARCHIVE_DIR="/var/log/mywebapp/archive"
RETENTION_DAYS=7

mkdir -p "$ARCHIVE_DIR"

# Find logs older than 1 day, archive and compress them
find "$LOG_DIR" -maxdepth 1 -type f -name "*.log" -mtime +0 -print0 | while IFS= read -r -d $'\0' log_file; do
    filename=$(basename "$log_file")
    timestamp=$(date +"%Y%m%d%H%M%S")
    tar -czvf "$ARCHIVE_DIR/${filename%.log}_${timestamp}.tar.gz" -C "$(dirname "$log_file")" "$filename"
    rm "$log_file"
    echo "Archived and compressed $filename"
done

# Remove archives older than retention days
find "$ARCHIVE_DIR" -type f -name "*.tar.gz" -mtime +"$RETENTION_DAYS" -delete
echo "Cleaned up archives older than $RETENTION_DAYS days."
How it works: This script automates log file management. It first defines log and archive directories, and a retention period. It then finds .log files in LOG_DIR older than one day, archives and compresses them into a tarball in ARCHIVE_DIR with a timestamp, and then deletes the original log. Finally, it removes any compressed archives in ARCHIVE_DIR that are older than the specified RETENTION_DAYS.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs