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

 

posted @ 2018-05-14 17:47  丶老中医  阅读(7429)  评论(0编辑  收藏  举报
一切已经开始©2018 丶老中医