nginx日志切割

cat cut-nginx-log.sh

[root@ali-idn-pro-nginx-ps01 script]# cat /data/script/cut-nginx-log.sh
#!/bin/bash
LOGS_PATH=/data/log/nginx/
YESTERDAY=$(date +%Y%m%d)
#按天切割日志
mv ${LOGS_PATH}/access.log ${LOGS_PATH}/access-${YESTERDAY}.log
mv ${LOGS_PATH}/error.log ${LOGS_PATH}/error-${YESTERDAY}.log
#向nginx主进程发送USR1信号,重新打开日志文件,否则会继续往mv后的文件写数据的。原因在于:linux系统中,内核是根据文件描述符来找文件的。如果不这样操作导致日志切割失败。
kill -USR1 `ps axu | grep "nginx: master process" | grep -v grep | awk '{print $2}'`
#delete 15
day nginx log find ${LOGS_PATH} -type f -mtime +15 | xargs rm -f
exit
0

 

定时任务

#delete 15 day nginx log
00 00 * * * /bin/bash /data/script/cut-nginx-log.sh

 

按小时切割nginx日志

cat /data/cut_nginx_log.sh

 

#!/bin/bash
LOGS_PATH=/var/log/nginx/
BACKUP_PATH=/backup_nginx_logs/
YESTERDAY=$(date +%Y%m%d%H)

#切割日志
mv ${LOGS_PATH}/access.log ${BACKUP_PATH}/access_${YESTERDAY}.log
mv ${LOGS_PATH}/error.log ${BACKUP_PATH}/error_${YESTERDAY}.log

#向nginx主进程发送USR1信号,重新打开日志文件,否则会继续往mv后的文件写数据的。
kill -USR1 `ps axu | grep "nginx: master process" | grep -v grep | awk '{print $2}'`

#压缩日志减少空开使用量
cd $BACKUP_PATH 
tar zcf access_$YESTERDAY.tar.gz access_$YESTERDAY.log
tar zcf error_$YESTERDAY.tar.gz error_$YESTERDAY.log

#删除7天前的日志和没压缩的日志文件
cd ${BACKUP_PATH}
find ${BACKUP_PATH} -mtime +7 -name "*.tar.gz" | xargs rm -f 
find ${BACKUP_PATH} -mtime +1 -name "*.log" | xargs rm -f
exit 0

 

定时任务:每个小时执行一次

00 */1 * * * bash /data/cut_nginx_log.sh

 

 

K8S部署nginx日志切割

cat cut_k8s_nginx_log.sh

for pod in $(kubectl get pods -n service-a | grep gateway | awk '{print $1}'); do 
  kubectl exec -ti -n service-a $pod -- /bin/mv /var/log/nginx/access.log /var/log/nginx/access.$(date +%F -d -1day).log
  kubectl exec -ti -n service-a $pod -- /usr/sbin/nginx -s reopen
done

配合定时任务定时切割

00 07 * * *  bash /data/scripts/cut_k8s_nginx_log.sh 

 

posted @ 2021-05-24 14:27  缺个好听的昵称  阅读(107)  评论(0编辑  收藏  举报