Nginx日志分割
使用方法(1)
30 23 * * * cd /home/ccodsupport/nginxLog && sudo ./nginxLog.sh &>/dev/null
#!/bin/bash
# 設(shè)置Nginx日志目錄
logdir="/home/nginx/logs"
# 查找所有日志文件
find "$logdir" -type f -name "*.log" | while read logfile; do
# 檢查文件是否存在
if [ -f "$logfile" ]; then
# 提取日期
date=`date +%F`
if [ -z "$date" ]; then
echo "Error: cannot extract date from $logfile"
continue
fi
# 創(chuàng)建新日志文件名
newlogfile="$logdir/$(basename "$logfile" .log)_$date.log"
# 將日志文件拆分為新文件
cp "$logfile" "$newlogfile"
> $logfile
fi
done
[nginx@ucloud_nginx_1 logs]$ ls -htrl
-rw-r--r-- 1 nginx nginx 380M Apr 18 17:40 error_2023-04-18.log
-rw-r--r-- 1 nginx nginx 0 Apr 18 17:40 error.log
-rw-r--r-- 1 nginx nginx 55M Apr 18 17:40 access_2023-04-18.log
-rw-r--r-- 1 nginx nginx 737K Apr 18 17:40 zabbix_2023-04-18.log
-rw-r--r-- 1 nginx nginx 895 Apr 18 17:50 access.log
-rw-r--r-- 1 nginx nginx 210 Apr 18 17:50 zabbix.log
使用方法(2)
- 使用 nginx 本身來實現(xiàn)
- 對應(yīng)在主配置文件server塊中修改
if ($time_iso8601 ~ "^(\d{4})-(\d{2})-(\d{2})") {
set $year $1;
set $month $2;
set $day $3;
}
access_log /var/log/nginx/${year}_${month}_${day}_access.log main;