Nginx日志分割(nginx日志详解)
```bash
#!/bin/bash
# 常量定义
nginx_log_dir="/var/log/nginx"
nginx_pid_file="/var/run/nginx.pid"
nginx_log_file="$nginx_log_dir/access.log"
MAX_LOG_SIZE_MB=500
SPLIT_LINES=50000
# 时间戳
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
if ! split -l $SPLIT_LINES "$log_file" "${log_file}_part"; then
echo "Failed to split log file."
exit 1
fi
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
}
# 重启 Nginx
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."
exit 1
fi
else
echo "Nginx PID file $nginx_pid_file does not exist."
exit 1
fi
}
# 主逻辑
nginx_log_split() {
local log_file="$nginx_log_file"
if file_exists "$log_file"; then
local log_size=$(stat -c%s "$log_file")
local log_size_mb=$((log_size / 1024 / 1024))
if [ "$log_size_mb" -gt $MAX_LOG_SIZE_MB ]; then
echo "Log file size is greater than ${MAX_LOG_SIZE_MB}MB. Splitting the log file."
rotate_log_file "$log_file"
restart_nginx
split_and_rm_log_file "${log_file}-${date_time}"
elif [ "$log_size_mb" -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
```