BASH

Basic Log Archiving with Date Stamping

A bash script to automate the archiving of log files by date-stamping them and optionally compressing, helping manage server disk space and log history.

#!/bin/bash

LOG_DIR="/var/log/mywebapp"
ARCHIVE_DIR="/var/log/mywebapp/archive"
LOG_FILE="access.log"

DATE=$(date +%Y%m%d%H%M%S)

# Create archive directory if it doesn't exist
mkdir -p "$ARCHIVE_DIR" || { echo "Error: Could not create archive directory $ARCHIVE_DIR"; exit 1; }

FULL_LOG_PATH="$LOG_DIR/$LOG_FILE"
ARCHIVED_LOG_PATH="$ARCHIVE_DIR/${LOG_FILE}.${DATE}.gz"

if [ -f "$FULL_LOG_PATH" ]; then
    echo "Archiving '$FULL_LOG_PATH' to '$ARCHIVED_LOG_PATH'..."
    gzip -c "$FULL_LOG_PATH" > "$ARCHIVED_LOG_PATH" || { echo "Error: Failed to gzip log file"; exit 1; }
    
    # Clear the original log file after archiving
    echo "" > "$FULL_LOG_PATH" || { echo "Error: Failed to clear original log file"; exit 1; }
    echo "Log file archived and cleared successfully."
else
    echo "Log file '$FULL_LOG_PATH' not found, skipping archiving."
fi

# Optional: Remove old archives (e.g., older than 30 days)
# find "$ARCHIVE_DIR" -type f -name "*.gz" -mtime +30 -delete
How it works: This script automates the archiving of a specified log file. It creates a gzip-compressed copy of the log, appending a date timestamp to its name, and stores it in a dedicated archive directory. After successful archiving, it clears the content of the original log file. An optional, commented-out line demonstrates how to automatically remove old archives, which is crucial for maintaining disk space and managing log retention policies.

Need help integrating this into your project?

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

Hire DigitalCodeLabs