linux脚本能轮循吗,linux下日志定时轮询的流程详解

logrotate介绍

对于Linux系统安全来说,日志文件是极其重要的工具。日志文件包含了关于系统中发生的事件的有用信息,在排障过程中或者系统性能分析时经常被用到。当日志文件不断增长的时候,就需要定时切割,否则,写日志的速度和性能也会下降,更不便于我们归档,查询。

所以便有了使用logrotate的时候 ,logrotate是个十分有用的工具,它可以自动对日志进行截断(或轮循)、压缩以及删除旧的日志文件。例如,你可以设置logrotate,让/var/log/foo日志文件每30天轮循,并删除超过6个月的日志。配置完后,logrotate的运作完全自动化,不必进行任何进一步的人为干预。

logrotate配置文件位置

Linux系统默认安装logrotate工具,它默认的配置文件在:

/etc/logrotate.conf

/etc/logrotate.d/

logrotate.conf 才主要的配置文件,logrotate.d 是一个目录,该目录里的所有文件都会被主动的读入/etc/logrotate.conf中执行。

另外,如果 /etc/logrotate.d/ 里面的文件中没有设定一些细节,则会以/etc/logrotate.conf这个文件的设定来作为默认值。

实际运行时,Logrotate会调用配置文件/etc/logrotate.conf。

可以在/etc/logrotate.d目录里放置自定义好的配置文件,用来覆盖Logrotate的缺省值。

定时轮循机制

Logrotate是基于CRON来运行的,其脚本是/etc/cron.daily/logrotate,日志轮转是系统自动完成的。

logrotate这个任务默认放在cron的每日定时任务cron.daily下面 /etc/cron.daily/logrotate

/etc/目录下面还有cron.weekly/, cron.hourly/, cron.monthly/ 的目录都是可以放定时任务的

[/etc]$ cat /etc/cron.daily/logrotate

#!/bin/sh

# Clean non existent log file entries from status file

cd /var/lib/logrotate

test -e status || touch status

head -1 status > status.clean

sed 's/"//g' status | while read logfile date

do

[ -e "$logfile" ] && echo "\"$logfile\" $date"

done >> status.clean

mv status.clean status

test -x /usr/sbin/logrotate || exit 0

/usr/sbin/logrotate /etc/logrotate.conf

这里实际操作轮询的命令最后一行

/usr/sbin/logrotate /etc/logrotate.conf

定义好了每日执行任务的脚本cron.daily/logrotate ,再查看crontab的内容,里面设置好了对应的cron.xxly

执行时间

[/etc]$ vim /etc/crontab

SHELL=/bin/sh

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin

# m h dom mon dow user command

17 * * * * root cd / && run-parts --report /etc/cron.hourly

25 6 * * * root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.daily )

47 6 * * 7 root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.weekly )

52 6 1 * * root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.monthly )

可以看出来了只要是在

/etc/cron.daily/ 下面的任务都是每天6:25 执行

/etc/cron.weekly/ 下面的任务都是每周日 6:47 执行

/etc/cron.monthly/ 下面的任务都是每月1号 6:52 执行

如果等不及cron自动执行日志轮转,想手动强制切割日志,需要加-f参数;

不过正式执行前最好通过Debug选项来验证一下(-d参数),这对调试也很重要

# /usr/sbin/logrotate -f /etc/logrotate.d/nginx // 未到时间或者未到切割条件,强制切割

# /usr/sbin/logrotate -d -f /etc/logrotate.d/nginx // 输出切割debug信息

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值