Linux中Nginx日志定时备份及清理

葛大爷 互联网 2018-12-06 470
  1. 创建日志备份脚本 nginx_log.sh
    #!/bin/bash
    echo [BASH] Start backup log
    logs_path="/usr/local/nginx/logs/"
    echo [BASH] Log directory ${logs_path}
    pid_path="/var/run/nginx.pid"
    echo [BASH] Pid directory ${pid_path}
    new_logs_path=${logs_path}$(date -d "yesterday" +"%Y%m%d")
    echo [BASH] Create new log directory ${new_logs_path}
    mkdir ${new_logs_path}
    echo [BASH] Start transferring logs
    mv ${logs_path}*.log ${new_logs_path}/
    echo [BASH] Regenerate logs
    kill -USR1 `cat ${pid_path}`
    new_logs_path=${logs_path}$(date -d "30 days ago" +"%Y%m%d")
    echo [BASH] Delete old log directory ${new_logs_path}
    rm -rf ${new_logs_path}
    echo [DONE]
  2. 添加定时任务
    #crontab -e
    0 0 * * * bash /opt/nginx_log.sh