linux nginx访问日志按天切割备份 并保留最近10天备份文件

  • Post author:
  • Post category:linux


#!/bin/bash

# Set the log directory and file names
LOG_DIR=/var/log/nginx/
ACCESS_LOG_FILE=access.log
ERROR_LOG_FILE=error.log

# Get the current date in the format yyyy-mm-dd
CURRENT_DATE=$(date +"%Y-%m-%d")

# Create the log files if they don't exist
if [ ! -f "$LOG_DIR$ACCESS_LOG_FILE" ]; then
  touch "$LOG_DIR$ACCESS_LOG_FILE"
fi

if [ ! -f "$LOG_DIR$ERROR_LOG_FILE" ]; then
  touch "$LOG_DIR$ERROR_LOG_FILE"
fi

# Rotate the access log file if the date has changed
if [ "$CURRENT_DATE" != "$(date -r "$LOG_DIR$ACCESS_LOG_FILE" +"%Y-%m-%d")" ]; then
  mv "$LOG_DIR$ACCESS_LOG_FILE" "$LOG_DIR"access-"$CURRENT_DATE".log
  systemctl reload nginx
fi

# Rotate the error log file if the date has changed
if [ "$CURRENT_DATE" != "$(date -r "$LOG_DIR$ERROR_LOG_FILE" +"%Y-%m-%d")" ]; then
  mv "$LOG_DIR$ERROR_LOG_FILE" "$LOG_DIR"error-"$CURRENT_DATE".log
  systemctl reload nginx
fi

# Archive previous day's log files
tar -czf "$LOG_DIR"access-"$CURRENT_DATE".tar.gz "$LOG_DIR"access-"$CURRENT_DATE".log
tar -czf "$LOG_DIR"error-"$CURRENT_DATE".tar.gz "$LOG_DIR"error-"$CURRENT_DATE".log

# Remove backup files older than 10 days
find "$LOG_DIR" -name "access-*.tar.gz" -type f -mtime +10 -delete
find "$LOG_DIR" -name "error-*.tar.gz" -type f -mtime +10 -delete



版权声明:本文为leeasj原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。