BASH

Automating Log Rotation and Compression

A bash script to automate log file rotation, compression, and cleanup of old archives, essential for maintaining server disk space and managing historical data.

#!/bin/bash

LOG_DIR="/var/log/mywebapp"
OLD_LOGS_DIR="$LOG_DIR/archive"
RETENTION_DAYS=30 # Keep compressed logs for 30 days

mkdir -p "$OLD_LOGS_DIR"

# Rotate current logs
for logfile in "$LOG_DIR"/*.log; do
    if [ -f "$logfile" ]; then
        filename=$(basename "$logfile" .log)
        timestamp=$(date +"%Y%m%d%H%M%S")
        mv "$logfile" "$OLD_LOGS_DIR/${filename}_${timestamp}.log"
    fi
done

# Compress rotated logs
find "$OLD_LOGS_DIR" -maxdepth 1 -name "*.log" -type f -print0 | while IFS= read -r -d $'\0' file; do
    gzip "$file"
done

# Delete old compressed logs
find "$OLD_LOGS_DIR" -maxdepth 1 -name "*.gz" -type f -mtime +"$RETENTION_DAYS" -delete
How it works: This script first creates an archive directory if it doesn't exist. It then moves all `.log` files from the specified `LOG_DIR` into the `OLD_LOGS_DIR`, appending a timestamp to their names for unique identification. After rotation, it compresses all newly rotated `.log` files into `.gz` format to save disk space. Finally, it removes any compressed log files (`.gz`) from the archive directory that are older than `RETENTION_DAYS`, ensuring efficient log management.

Need help integrating this into your project?

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

Hire DigitalCodeLabs