nginx日志access.log error.log按天生成存储,定时删除日志

来源:互联网 发布:mac地址软件下载 编辑:程序博客网 时间:2024/05/02 05:04

问题:nginx会按照nginx.conf的配置生成access.log和error.log,随着访问量的增长,日志文件会越来越大,既会影响访问的速度(写入日志时间延长),也会增加查找日志的难度,nginx没有这种按天或更细粒度生成日志的机制,所以需要自己添加定时任务,分割日志文件。

1.新建分割日志文件的脚本,例如存放路径:/usr/local/nginx/sbin/cut_nginx_logs.sh,按天分割具体内容:

#!/bin/bash
#function:cut nginx log files for lnmp v0.5 and v0.6
#author: http://lnmp.org


#set the path to nginx log files
log_files_path="/data/nginxlog/"
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="/usr/local/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 {} \; 


$nginx_sbin -s reload

2.将脚本添加到定时任务中,我指定每天0点执行

//打开定时任务

crontab -e

//进入编辑模式

i

//添加定时任务

00 00 * * * /bin/sh  /usr/local/nginx/sbin/cut_nginx_logs.sh

//保存退出

:wq

//查看定时任务,就会看到你添加的内容了

crontab -l

3.查看实际效果



0 0