一 简介
对于nginx的日志文件,特别是access日志,如果我们不做任何处理的话,最后这个文件将会变得非常庞大,比如像下面这样:
这时,无论是出现异常时查日志,还是使用“GoAccess”等工具对日志进行分析都将会变得非常麻烦。因此,每天定时对nginx日志进行切割压缩就非常有必要了
二 实现
我的实现思路是每天晚上接近12点时定时执行脚本。其脚本内容就是将当前的nginx日志先按照当天日期进行重命名接着进行压缩,最后是新建空白的nginx日志文件,并重新载入nginx
1
2
3
|
[
root
@
localhost
~
]
# cd /usr/local
[
root
@
localhost
local
]
# mkdir scripts
[
root
@
localhost
scripts
]
# vim nginxLog.sh
|
其内容如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
#!/bin/sh
cd
/
usr
/
local
/
nginx
/
logs
/
newAccessLog
=
"access`date +%Y-%m-%d`.log"
newErrorLog
=
"error`date +%Y-%m-%d`.log"
mv
access
.log
$newAccessLog
mv
error
.log
$newErrorLog
#创建日志文件
touch
access
.log
error
.log
#reload Nginx
/
etc
/
init
.d
/
nginx
reload
#压缩日志文件
tar
-
zcvf
$newAccessLog
.tar
.gz
$newAccessLog
--
remove
-
files
tar
-
zcvf
$newErrorLog
.tar
.gz
$newErrorLog
--
remove
-
files
|
给脚本添加可执行权限:
1
|
[
root
@
localhost
scripts
]
# chmod a+x nginxLog.sh
|
添加定时任务(每天23:40执行):
1
2
|
[
root
@
localhost
scripts
]
# cd /var/spool/cron/
[
root
@
localhost
cron
]
# echo "40 23 * * * /usr/local/scripts/nginxLog.sh" > root
|
查看任务:
1
|
[
root
@
localhost
cron
]
# crontab -l
|
这样,第二天就可以看到效果了。最后的效果如下图所示:
注:如果有多个nginx日志文件的话可以考虑将我上面的脚本改成更加通用的形式
附:nginx日志定时清理脚本:
1
|
[
root
@
localhost
scripts
]
# vim /usr/local/scripts/cleanNginxLog.sh
|
其内容如下:
1
2
3
4
|
#!/bin/sh
cd
/
usr
/
local
/
nginx
/
logs
/
find
.
-
name
"*`date -d '-1months' +%Y-%m-%d`*"
-
type
f
|
xargs
-
I
{
}
rm
-
f
{
}
|
注:上面脚本的意思是删除当前天之前一个月那天的日志文件
给脚本添加可执行权限:
1
|
[
root
@
localhost
scripts
]
# chmod a+x /usr/local/scripts/cleanNginxLog.sh
|
添加一条定时任务(每天0:30执行):
1
|
[
root
@
localhost
scripts
]
# echo "30 0 * * * /usr/local/scripts/cleanNginxLog" >> /var/spool/cron/root
|