nginx日志按天生成和定期删除日志的方法

 更新时间:2017年7月6日 23:16  点击:1368

问题:nginx会按照nginx.conf的配置生成access.log和error.log,随着访问量的增长,日志文件会越来越大,既会影响访问的速度(写入日志时间延长),也会增加查找日志的难度,nginx没有这种按天或更细粒度生成日志的机制。所以下面介绍两种方法:1.写脚本,通过定时任务按天重命名日志、重启nginx的方法实现(有重启失败的风险)2.通过工具cronolog实现。推荐方法二。

1.方法一:创建分割日志文件的脚本,添加定时任务

1.1写脚本:重命名日志文件、重启nginx

例如存放路径:/usr/local/nginx/sbin/cut_nginx_logs.sh,按天分割具体内容:

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

#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 {} \; 

#restart nginx
$nginx_sbin -s reload

1.2.使用crontab添加定时任务

//打开定时任务
crontab -e
//进入编辑模式
i
//添加定时任务
00 00 * * * /bin/sh /usr/local/nginx/sbin/cut_nginx_logs.sh
//保存退出
:wq!
//重启crontab服务
/etc/init.d/crond restart
//查看定时任务,就会看到你添加的内容了
crontab -l

2. 方法二:通过cronolog工具实现

2.1 下载安装cronolog

2.1.1 下载:下载

2.1.2 安装

1.解压缩

# tar zxvf cronolog-1.6.2.tar.gz

2.进入安装文件所在目录

# cd cronolog-1.6.2

3.运行安装

# ./configure
# make
# make install

4.查看cronolog安装后所在目录(验证安装是否成功)

# which cronolog

一般情况下显示为:/usr/local/sbin/cronolog

2.2 使用cronolog

2.2.1.创建命名管道

mkfifo /usr/local/nginx/access_log_pipe

2.2.2 配置cronolog,日期按天

如果按小时使用access_%Y-%m-%d-%H.log;如果按分钟使用access_%Y-%m-%d-%H-%M.log

2.2.3 修改配置/usr/local/nginx/conf/nginx.conf

...
access_log /usr/local/nginx/access_log_pipe main;
...

nohup cat /usr/local/nginx/access_log_pipe | /usr/local/sbin/cronolog /usr/local/nginx/logs/access-%Y-%m-%d.log &

2.2.4 重启nginx

cd /usr/local/nginx/sbin
./nginx -s reload

2.2.5 查看效果

[root@app2 /]# cd /usr/local/nginx/logs/
[root@app2 logs]# ll
total 3544
-rw-r--r-- 1 root root    0 Oct 1 07:20 8099.access.log
-rw-r--r-- 1 root root 3599534 Oct 1 07:58 access-2016-10-01.log
-rw-r--r-- 1 root root   235 Oct 1 07:20 error.log
-rw-r--r-- 1 root root    5 Oct 1 06:34 nginx.pid

2.3 定期删除日志

2.3.1 新建sh,删除5天前的

[root@app2 sh]# pwd
/usr/local/nginx/sh
[root@app2 sh]# vi delete_nginx_logs.sh 

添加内容

#set the path to nginx log files
log_files_path="/usr/local/nginx/logs/"
save_days=5
#delete ? days ago nginx log files
find $log_files_path -mtime +$save_days -exec rm -rf {} \;

2.3.2 添加定时任务

[root@localhost sh]# crontab -e
00 00 * * * /bin/sh /usr/local/nginx/sh/delete_nginx_logs.sh

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

[!--infotagslink--]

相关文章