nginx日志分割

2024-01-14  本文已影响0人  平凡的运维之路

Nginx日志分割

使用方法(1)

30 23 * * * cd /home/ccodsupport/nginxLog && sudo ./nginxLog.sh &>/dev/null
#!/bin/bash

# 设置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
    # 创建新日志文件名
    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)

     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;
上一篇 下一篇

猜你喜欢

热点阅读