分享一个将当天应用产生的日志进行压缩归档,并且删除一个月当天的日志。

#!/bin/bash

LOG_SOURCE_DIR="应用系统的日志路径"
ARCHIVE_DIR="/data/log/archive"

# Create archive directory if it doesn't exist
mkdir -p "$ARCHIVE_DIR" || {
    echo "ERROR: Failed to create archive directory $ARCHIVE_DIR" >&2
    exit 1
}

TEMP_DIR=$(mktemp -d -t daily_logs_$(date +%Y%m%d)_XXXXXX) || {
    echo "ERROR: Failed to create temp directory" >&2
    exit 1
}

echo "Using temp directory: $TEMP_DIR"

TODAY=$(date +%Y-%m-%d)
LAST_MONTH=$(date -d "1 month ago" "+%Y-%m-%d")

echo "Finding and copying today's logs..."

# Find and copy today's log files
find "$LOG_SOURCE_DIR" -type f \( -name "*$TODAY*" \) -exec cp {} "$TEMP_DIR" \;

FILE_COUNT=$(ls -1 "$TEMP_DIR" 2>/dev/null | wc -l)
if [ "$FILE_COUNT" -gt 0 ]; then
    echo "Compressing $FILE_COUNT files..."
    tar -czvf "$ARCHIVE_DIR/logs_$TODAY1.tar.gz" -C "$TEMP_DIR" . || {
        echo "ERROR: Compression failed" >&2
    }
else
    echo "WARNING: No logs found for today"
fi

rm -rf "$TEMP_DIR"
echo "Temp directory cleaned"

# Check disk usage (this was missing in original script)
usage=$(df -P /data | awk 'NR==2 {print $5}' | tr -d '%')
echo "Disk usage: $usage%"
if [ "$usage" -gt 80 ]; then
   echo "Clearing nohup.out due to high disk usage"
   find 应用日志的nohup.out路径 -type f -name "nohup.out" -exec truncate -s 0 {} \;
else
   echo "Disk usage normal, no action taken"
fi

echo "Deleting logs from $LAST_MONTH"
find "$LOG_SOURCE_DIR" -type f -name "*$LAST_MONTH*" -delete

echo "Cleanup completed at $(date)"