Nginx 日志文件切割

楔子

阿里云的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”是更通用的方法,推荐使用!

参考

Linux shell 获取格式化时间
Linux定时任务在线计算
定时任务

删除文件2种方法比较

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值