shell脚本-Nginx访问日志自动按天切割
shell脚本-Nginx访问日志自动按天切割
前言
日志如果一直不归档分类,access.log文件会逐渐增大,后续难以获取相应信息。
1.通过kill USR1 nginx.pid 可以创建新的access.log文件,所以我们每天整点把前一天的log日志文件移动指定文件夹下,再创建一个新的access.log文件记录当日的日志即可
kill USR1 `/usr/local/nginx/logs/nginx.pid`
2.而nginx.pid也记录在/usr/local/nginx/logs/nginx.pid,或者/var/run/nginx.pid下面
shell脚本
#!/bin/bash # 将每天给的log日志文件按月份归档 # 例如 /usr/local/nginx/logs/2023-7/access.log_2023-7-16 LOG_DIR=/usr/local/nginx/logs YESTERDAY_TIME=`date -d "yesterday" +%F` LOG_MONTH_DIR=$LOG_DIR/`date +"%Y-%m"` LOG_FILE_LIST="access.log" for LOG_FILE in $LOG_FILE_LIST;do [ ! -d $LOG_MONTH_DIR ] && mkdir -p $LOG_MONTH_DIR mv $LOG_DIR/$LOG_FILE $LOG_MONTH_DIR/${LOG_FILE}_${YESTERDAY_TIME} done kill -USR1 `cat /usr/local/nginx/logs/nginx.pid`
[root@localhost logs]# ls access.log error.log nginx.pid [root@localhost logs]# bash /opt/scripts/14.sh [root@localhost logs]# ls 2023-07 access.log error.log nginx.pid [root@localhost logs]# cd 2023-07/ [root@localhost 2023-07]# ls access.log_2023-07-16 [root@localhost 2023-07]# cat access.log_2023-07-16 192.168.70.1 - [17/Jul/2023:23:44:35 +0800] "GET / HTTP/1.1" 200 173829 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36 Edg/114.0.1823.82" "-"