nginx日志按天生成&定期刪除日志


nginx日志按天生成&定期刪除日志

創建分割日志文件的腳本,添加定時任務

首先配置nginx.conf:

#error_log  logs/error.log;
#error_log  logs/error.log  notice;
#error_log  logs/error.log  info;

pid        logs/nginx.pid; //否則會找不到nginx.pid(#刪除)

log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"'
                       '$upstream_addr $upstream_response_time $request_time '; # 規定 格式

access_log  logs/access.log  main; #開啟access.log

 

重命名日志文件、重啟nginx

例如存放路徑:/opt/runtime/nginx/logs/cut_nginx_logs.sh,按天分割具體內容:

#!/bin/bash
#function:cut nginx log files

#set the path to nginx log files
log_files_path="/opt/runtime/nginx/logs/"
log_files_dir=${log_files_path}
#set nginx log files you want to cut
log_files_name=(access )
#set the path to nginx.
nginx_sbin="/opt/runtime/nginx/sbin/nginx"
#Set how long you want to save
save_days=30
############################################
#Please do not modify the following script #
############################################
#mkdir -p $log_files_dir
log_files_num=${#log_files_name[@]}

#cut nginx log files
for((i=0;i<$log_files_num;i++));do
mv ${log_files_path}${log_files_name[i]}.log ${log_files_dir}${log_files_name[i]}.log_$(date -d "yesterday" +"%Y-%m-%d")
done

#delete 30 days ago nginx log files
find $log_files_path -mtime +$save_days -exec rm -rf {} \; 

#重新創建access.log文件
touch access.log
chown nignx:nignx access.log
#restart nginx $nginx_sbin
-s reload

使用crontab添加定時任務

//打開定時任務
crontab -e
//進入編輯模式
i
//添加定時任務
00 00 * * * /bin/sh  /opt/runtime/nginx/logs/cut_nginx_logs.sh
//保存退出
:wq!
//重啟crontab服務
/etc/init.d/crond restart
//查看定時任務,就會看到你添加的內容了
crontab -l

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM