JAVA和Nginx 教程大全

网站首页 > 精选教程 正文

只使用Shell脚本进行Nginx访问日志access_log的轮询切割

wys521 2024-09-17 02:42:14 精选教程 30 ℃ 0 评论

默认情况Nginx会把所有的访问日志生成到一个指定的访问日志文件access.log里,但这样一来,时间长了就会导致日志个头很大,不利于日志的分析和处理,因此,有必要对Nginx日志、按天或按小时进行切割,使其分成不同的文件保存。这里使用按天切割的方法。

这里使用Shell脚本+ 计划任务来进行日志轮询切割,具体的脚本如下:

[root@private shell]# cat nginx_cut_log.sh

#!/bin/bash

date_format=$(date +%Y%m%d)

nginx_dir="/usr/local/nginx"

nginx_log_dir="$nginx_dir/logs"

log_name="access_blog"

[ -d $nginx_log_dir ] && cd $nginx_log_dir || exit 1

[ -f ${log_name}.log ] || exit 1

/bin/mv ${log_name}.log ${date_format}_${log_name}.log

$nginx_dir/sbin/nginx -s reload

[root@private shell]#

注意:脚本实现切割Nginx日志的思想为将正在写入的Nginx日志(access_www.log)改名为带日期的格式文件(20171021_access_www.log),然后平滑重新加载Nginx,生成新的Nginx日志(access_www.log)。

下面通过定时任务实现每天00点整定时执行/root/Script/shell/nginx_cut_log.sh切割日志。

[root@private shell]# cat >> /var/spool/cron/root << EOF

> # cut nginx access log by oldboy

> 00 00 * * * /bin/bash /root/Script/shell/nginx_cut_log.sh > /dev/null 2>&1

> EOF

[root@private shell]# crontab -l

*/5 * * * * /usr/sbin/ntpdate ntp.api.bz

# cut nginx access log by oldboy

00 00 * * * /bin/bash /root/Script/shell/nginx_cut_log.sh > /dev/null 2>&1

[root@private shell]#

执行脚本进行结果验证:

[root@private shell]# ls nginx_cut_log.sh

nginx_cut_log.sh

[root@private shell]# bash nginx_cut_log.sh

[root@private shell]# ls /usr/local/nginx/logs/

20171021_access_blog.logaccess_blog.logaccess.logerror.lognginx.pid

[root@private shell]#

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表