← Back to all snippets
BASH

Implementing Basic Log File Rotation

Manage growing log files by implementing a simple Bash script for rotation, compression, and deletion of old logs, preventing disk space exhaustion on servers.

#!/bin/bash
LOG_DIR="/var/log/mywebapp"
LOG_FILE="$LOG_DIR/app.log"
MAX_LOG_FILES=5 # Keep the current + 4 archived logs
DATE_FORMAT="+%Y%m%d_%H%M%S"

mkdir -p "$LOG_DIR" # Ensure log directory exists

# 1. Rotate current log file if it exists and is not empty
if [ -s "$LOG_FILE" ]; then
    echo "Rotating $LOG_FILE..."
    mv "$LOG_FILE" "$LOG_FILE.$(date "$DATE_FORMAT")"
    touch "$LOG_FILE" # Create a new empty log file
else
    echo "Log file $LOG_FILE is empty or does not exist. No rotation needed."
fi

# 2. Compress old log files (optional)
find "$LOG_DIR" -maxdepth 1 -type f -name 'app.log.*' ! -name '*.gz' -exec gzip {} \;

# 3. Delete oldest compressed log files to maintain MAX_LOG_FILES count
# Note: `sort -V` for version-like sorting to ensure correct order
find "$LOG_DIR" -maxdepth 1 -type f -name 'app.log.*.gz' | sort -rV | tail -n +$MAX_LOG_FILES | xargs -r rm

echo "Log rotation complete for $LOG_FILE_BASE."
How it works: This script handles basic log file rotation. It renames the current log with a timestamp, creates a new empty one, optionally compresses older logs, and then deletes the oldest compressed logs to keep the number of archived files within a specified limit. This helps manage disk space and log file size for web server applications.

Need help integrating this into your project?

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

Hire DigitalCodeLabs