nginx 日志处理
#!/bin/bash
nginx_log_dir="/var/log/nginx"
nginx_pid_file="nginx.pid"
nginx_log_file="access.log"
date_time=$(date +%Y-%m-%d_%H-%M-%S) # 避免同一秒内多次运行导致文件名冲突
# 检查文件是否存在
file_exists() {
local file="$1"
if [ ! -f "$file" ]; then
echo "File $file does not exist."
return 1
fi
return 0
}
split_and_rm_log_file() {
local log_file="$1"
if file_exists "$log_file"; then
split -l 50000 "$log_file" "${log_file}_part"
rm "$log_file"
fi
}
rotate_log_file() {
local log_file="$1"
if file_exists "$log_file"; then
mv "$log_file" "${log_file}-${date_time}"
fi
}
restart_nginx() {
if file_exists "$nginx_pid_file"; then
local nginx_pid=$(cat "$nginx_pid_file")
if kill -0 "$nginx_pid" &> /dev/null; then
kill -USR1 "$nginx_pid"
else
echo "Nginx process with PID $nginx_pid does not exist."
fi
else
echo "Nginx PID file $nginx_pid_file does not exist."
fi
}
nginx_log_split() {
local log_file="$nginx_log_dir/$nginx_log_file"
if file_exists "$log_file"; then
local log_size=$(du -m "$log_file" | cut -f1)
if [ "$log_size" -gt 500 ]; then
echo "Log file size is greater than 500MB. Splitting the log file."
rotate_log_file "$log_file"
restart_nginx
split_and_rm_log_file "${log_file}-${date_time}"
elif [ "$log_size" -eq 0 ]; then
echo "Log file size is 0MB. No action needed."
fi
else
echo "Log file $log_file does not exist."
fi
}
nginx_log_split