BASH
Basic Log File Archiving
Perform simple rotation for application log files. This script archives old log files by compressing and renaming them with a timestamp, then truncates the original log file for fresh logging.
#!/bin/bash
LOG_FILE=$1
ARCHIVE_DIR="logs_archive"
if [ -z "$LOG_FILE" ]; then
echo "Usage: $0 <path_to_log_file>"
echo "Example: $0 /var/log/myapp/access.log"
exit 1
fi
if [ ! -f "$LOG_FILE" ]; then
echo "Error: Log file '$LOG_FILE' not found."
exit 1
fi
mkdir -p "$ARCHIVE_DIR"
TIMESTAMP=$(date +"%Y%m%d_%H%M%S")
FILENAME=$(basename "$LOG_FILE")
ARCHIVED_NAME="${ARCHIVE_DIR}/${FILENAME}_${TIMESTAMP}.tar.gz"
echo "Archiving '$LOG_FILE' to '$ARCHIVED_NAME'..."
tar -czf "$ARCHIVED_NAME" "$LOG_FILE"
if [ $? -eq 0 ]; then
echo "Archive created successfully. Truncating original log file..."
# Truncate the original log file
> "$LOG_FILE"
echo "Log file '$LOG_FILE' truncated."
else
echo "Error: Failed to create archive for '$LOG_FILE'."
exit 1
fi
How it works: This script provides a basic method for archiving application log files. It takes the path to a log file as an argument. It creates an `logs_archive` directory, then compresses the specified log file using `tar -czf` with a timestamp in its name. Upon successful archiving, it truncates the original log file, making it ready for new log entries.