Nginx日志按天分割与定期清理的两种实现方案
问题:Nginx依据nginx.conf配置生成access.log和error.log,随着访问量增加,日志文件体积不断膨胀,不仅延长写入时间影响访问速度,也增加了日志检索难度。由于Nginx自身缺乏按天或更细粒度自动分割日志的机制,因此需要借助外部手段解决。以下介绍两种实现方式:一是编写脚本并通过定时任务按天重命名日志后重启Nginx(存在重启失败风险);二是使用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-2026-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
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持本站。