您现在的位置是:首页 >技术教程 >自动化清理Nginx日志:定时删除30天前的过期日志文件网站首页技术教程

自动化清理Nginx日志:定时删除30天前的过期日志文件

reddddddddddddd 2025-03-05 12:01:01
简介自动化清理Nginx日志:定时删除30天前的过期日志文件

自动化清理Nginx日志:定时删除30天前的过期日志文件

脚本编写:

#!/bin/bash

# Nginx 日志目录
log_dir="/usr/local/nginx-1.20.1/logs"

# 查找并删除超过 30 天的 .log 和 .gz 格式的日志文件
find "$log_dir" -type f ( -name "*.log" -o -name "*.gz" ) -mtime +30 -exec rm -f {} ;

# 输出清理信息
echo "Nginx 日志文件清理完成 $(date)"

解释:

  1. log_dir="/usr/local/nginx-1.20.1/logs": 你提供的日志目录路径。
  2. find "$log_dir" -type f ( -name "*.log" -o -name "*.gz" ) -mtime +30 -exec rm -f {} ;:
    • find "$log_dir": 查找指定目录中的文件。
    • -type f: 查找文件类型为普通文件。
    • ( -name "*.log" -o -name "*.gz" ): 查找 .log.gz 格式的文件。
    • -mtime +30: 查找修改时间超过30天的文件。
    • -exec rm -f {} ;: 删除找到的文件。
  3. echo "Nginx 日志文件清理完成 $(date)": 输出日志清理完成的时间,便于后续检查。

使脚本可执行:

  1. 将脚本保存为 clear_nginx_logs.sh 文件。
  2. 赋予脚本执行权限:
chmod +x clear_nginx_logs.sh

设置定时任务(Cron):

为了自动化执行清理操作,你可以将脚本添加到 cron 中,使其每天执行一次,清理超过30天的日志。

  1. 编辑 crontab 配置:
crontab -e
  1. 添加以下定时任务(每天凌晨 12 点执行脚本):
0 0 * * * /path/to/your/clear_nginx_logs.sh >> /var/log/nginx/log_cleanup.log 2>&1
  • /path/to/your/clear_nginx_logs.sh 替换为脚本的实际路径。
  • >> /var/log/nginx/log_cleanup.log 2>&1 用于将输出日志重定向到 /var/log/nginx/log_cleanup.log 文件中,方便查看脚本执行情况。
风语者!平时喜欢研究各种技术,目前在从事后端开发工作,热爱生活、热爱工作。