楔子
阿里云的Nginx好久没查看过日志,现在需要配置定时任务实现,日志文件切割,并删除超过30天的日志文件。
日志文件切割
- 把旧文件A拷贝到 指定目录(这时 Nginx还会继续在旧文件A中写日志)
- 调用nginx -s reopen ,nginx日志就会写入新的文件中
定时任务
log.sh
脚本文件
#!/bin/bash
#获取当前时间 yyyy-MM-dd_HH_mm_ss 格式
nowtime=`date "+%Y-%m-%d_%H_%M_%S"`
cd /usr/local/nginx
mv logs/error.log ./logbak/${nowtime}_error.log
mv logs/access.log ./logbak/${nowtime}_access.log
nginx -s reopen # 执行者条语句 ,确认 nginx 命令的位置
# 上面也可以用 kill -USR1 $(cat /usr/local/nginx/logs/nginx.pid)
# 删除30之气的文件
find /usr/local/nginx/logbak -ctime +30 -type f | xargs rm -rf
定时任务
crontab -e
来添加定时任务
00 04 1 * * /usr/local/nginx/log.sh
[root@centos64 logs]# crontab -u grq
crontab: usage error: file name must be specified for replace
Usage:
crontab [options] file
crontab [options]
crontab -n [hostname]
#定时任务选项,如果不指定用户,则表示当前登录的用户
Options:
-u <user> define user
-e edit user's crontab
-l list user's crontab
-r delete user's crontab
-i prompt before deleting
-n <host> set host in cluster to run users' crontabs
-c get host in cluster to run users' crontabs
-s selinux context
-x <mask> enable debugging
-----------------------------------------
[root@centos64 logs]# more /etc/crontab
SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root
# For details see man 4 crontabs
# Example of job definition:
# .---------------- minute (0 - 59)分
# | .------------- hour (0 - 23)时
# | | .---------- day of month (1 - 31)日
# | | | .------- month (1 - 12) OR jan,feb,mar,apr ...月
# | | | | .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat周
# | | | | |
# * * * * * user-name command to be executed
[root@centos64 logs]#
删除指定时间之前的文件
1
#只保留30之内文件,其余文件删除
find /usr/local/nginx/logbak -mtime +30 -type f -name *.log -exec rm -rf {} \;
/usr/local/nginx/logbak --设置查找的目录;
-mtime +30 --设置时间为30天前;
-type f --设置查找的类型为文件;
-name *.log --设置文件名称中包含mail1或者mail2;
-exec rm -f --查找完毕后执行删除操作;
2
find . -ctime +40 -type f | xargs rm -rf
上述两者比较
两者都可以把find命令查找到的结果删除,其区别简单的说是前者是把find发现的结果一次性传给exec选项,这样当文件数量较多的时候,就可能会出现“参数太多”之类的错误,相比较而言,后者就可以避免这个错误,因为xargs命令会分批次的处理结果。这样看来,“find ./| xargs rm -rf”是更通用的方法,推荐使用!