← Back to all snippets
BASH

Automate Log Rotation and Compression

Learn how to automate log file rotation and compression in Bash, saving disk space and managing server logs efficiently for web applications.

#!/bin/bash

LOG_DIR="/var/log/myapp"
RETENTION_DAYS=7

echo "Starting log rotation for $LOG_DIR at $(date)"

# Create a rotated log file with a timestamp
find "$LOG_DIR" -type f -name "*.log" -exec bash -c 'mv "$0" "$0.bak_$(date +%Y%m%d%H%M%S)"' {} \;

# Compress the rotated logs
find "$LOG_DIR" -type f -name "*.bak_*" -exec gzip {} \;

# Remove old compressed logs
find "$LOG_DIR" -type f -name "*.gz" -mtime +"$RETENTION_DAYS" -delete

echo "Log rotation finished at $(date)"
How it works: This script automates the process of rotating and compressing log files. It first renames existing `.log` files by appending a timestamp, then compresses these newly rotated files using `gzip`. Finally, it deletes any compressed logs older than a specified number of `RETENTION_DAYS` to free up disk space, making it ideal for regular cron jobs.

Need help integrating this into your project?

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

Hire DigitalCodeLabs