使用logrotate对日志文件进行转储

  1. 查看logrotate由于哪些文件组成

     [root@localhost ~]# rpm -ql logrotate
    
    /etc/cron.daily/logrotate	//日志轮转脚本
    /etc/logrotate.conf			// 主配置文件,默认的配置文件,但是所有的日志使用一样定义的配置不灵活,也会会显得很多,所有一般都是子配置文件中,子配置文件的配置会覆盖主配置文件
    /etc/logrotate.d			// 子配置文件的目录,存放子配置文件
    /etc/rwtab.d/logrotate
    /usr/sbin/logrotate			// 二进制可执行文件
    /usr/share/doc/logrotate-3.8.6	
    /usr/share/doc/logrotate-3.8.6/CHANGES
    /usr/share/doc/logrotate-3.8.6/COPYING
    /usr/share/man/man5/logrotate.conf.5.gz
    /usr/share/man/man8/logrotate.8.gz
    /var/lib/logrotate			
    /var/lib/logrotate/logrotate.status		// 运行状态的文件,记录上一次运行的状态
    
  2. logrotate 参数

     [root@localhost ~]# logrotate --help
    
    用法: logrotate [OPTION...] <configfile>
      -d, --debug              // 只是测试效果,不会轮转日志
      -f, --force              // 强制轮转文件
      -m, --mail=command       // 发生邮件的命令
      -s, --state=statefile    // 运行状态文件的路径
      -v, --verbose            // 显示轮转的详细信息
      -l, --log=STRING         // 日志文件
      --version                // 显示版本信息
    
    Help options:				// 帮助参数
      -?, --help               // 展示帮助信息
      --usage                 //  简短的使用信息
    
  3. logrotate.conf 重要参数说明

    compress                                   通过gzip 压缩转储以后的日志
    nocompress                                不做gzip压缩处理
    copytruncate                              用于还在打开中的日志文件,把当前日志备份并截断;是先拷贝再清空的方式,拷贝和清空之间有一个时间差,可能会丢失部分日志数据。
    nocopytruncate                           备份日志文件不过不截断
    create mode owner group             轮转时指定创建新文件的属性,如create 0777 nobody nobody
    nocreate                                    不建立新的日志文件
    delaycompress                           和compress 一起使用时,转储的日志文件到下一次转储时才压缩
    nodelaycompress                        覆盖 delaycompress 选项,转储同时压缩。
    missingok                                 如果日志丢失,不报错继续滚动下一个日志
    errors address                           专储时的错误信息发送到指定的Email 地址
    ifempty                                    即使日志文件为空文件也做轮转,这个是logrotate的缺省选项。
    notifempty                               当日志文件为空时,不进行轮转
    mail address                             把转储的日志文件发送到指定的E-mail 地址
    nomail                                     转储时不发送日志文件
    olddir directory                         转储后的日志文件放入指定的目录,必须和当前日志文件在同一个文件系统
    noolddir                                   转储后的日志文件和当前日志文件放在同一个目录下
    sharedscripts                           运行postrotate脚本,作用是在所有日志都轮转后统一执行一次脚本。如果没有配置这个,那么每个日志轮转后都会执行一次脚本
    prerotate                                 在logrotate转储之前需要执行的指令,例如修改文件的属性等动作;必须独立成行
    postrotate                               在logrotate转储之后需要执行的指令,例如重新启动 (kill -HUP) 某个服务!必须独立成行
    daily                                       指定转储周期为每天
    weekly                                    指定转储周期为每周
    monthly                                  指定转储周期为每月
    rotate count                            指定日志文件删除之前转储的次数,0 指没有备份,5 指保留5 个备份
    dateext                                  使用当期日期作为命名格式
    dateformat .%s                       配合dateext使用,紧跟在下一行出现,定义文件切割后的文件名,必须配合dateext使用,只支持 %Y %m %d %s 这四个参数
    size(或minsize) log-size            当日志文件到达指定的大小时才转储,log-size能指定bytes(缺省)及KB (sizek)MB(sizem).
    当日志文件 >= log-size 的时候就转储。 以下为合法格式:(其他格式的单位大小写没有试过)
    size = 5 或 size 5>= 5 个字节就转储)
    size = 100k 或 size 100k
    size = 100M 或 size 100M
    
  4. 分析/etc/logrotate.d/nginx 日志轮转配置文件

    使用yum安装nginx就会自动生成日志轮转配置文件
    yum install epel-release -y
    yum -y install nginx
    systemctl start nginx

    /var/log/nginx/*.log {	//nginx日志文件所有绝对路径,可以指定通配符
        create 0640 nginx root	// 创建新文件时权限,所有者和属组
        daily					// 轮转周期是每天
        rotate 10				// 保留个数为10个
        missingok				// 如果日志丢失,不报错继续滚动下一个日志
        notifempty				// 当日志文件为空时,不进行轮转
        compress				// 通过gzip 压缩转储以后的日志
        delaycompress			// 和compress 一起使用时,转储的日志文件到下一次转储时才压缩
        sharedscripts			// 运行postrotate脚本,作用是在所有日志都轮转后统一执行一次脚本。如果没有配置这个,那么每个日志轮转后都会执行一次脚本,在多日志文件的时候一定要开启
        postrotate
            /bin/kill -USR1 `cat /run/nginx.pid 2>/dev/null` 2>/dev/null || true		// 重新打开nginx日志文件
        endscript
    }
    
  5. 使用logrotate命令手动完成·日志轮转
    5.1. 查看你原始的日志文件

     [root@localhost nginx]# ls /var/log/nginx/
     access.log  error.log
    

    5.2. 使用debug测试轮转过程,只是测试不会生效

    刚安装nginx是没有访问日志的,所有需要访问一下网页生成日志
    第一次使用logrotate -s /var/lib/logrotate/logrotate.status /etc/logrotate.d/nginx 是可以轮转日志的,但是后续不会轮转,应为轮转周期是1天

    1) 修改一下当前时钟时间,修改为明天

     date -s "20231219"		//修改的往后一点都没事
    

    2)测试

     logrotate -d /etc/logrotate.d/nginx
    
    reading config file /etc/logrotate.d/nginx
    Allocating hash table for state file, size 15360 B
    
    Handling 1 logs
    
    rotating pattern: /var/log/nginx/*.log  after 1 days (10 rotations)
    empty log files are not rotated, old logs are removed
    considering log /var/log/nginx/access.log
    ......
    removing old log /var/log/nginx/access.log.11.gz
    error: error opening /var/log/nginx/access.log.11.gz: 没有那个文件或目录
    

    运行测试结果后面有个报错,其实我们只保留10个日志,肯定是没有access.log.11.gz日志文件,所以可以忽略

    5.3. 手动运行日志轮转,并将运行状态写入到 /var/lib/logrotate/logrotate.status中,使用 -f 强制轮转

     logrotate -s /var/lib/logrotate/logrotate.status -f /etc/logrotate.d/nginx
    

    1)效果

     [root@localhost nginx]# ll
     -rw-r----- 1 nginx root     0 12月 19 00:09 access.log
     -rw-r----- 1 nginx root 17856 12月 16 13:41 access.log.1
     -rw-r--r-- 1 nginx root     0 12月 16 11:50 error.log
     [root@localhost nginx]# head access.log
     [root@localhost nginx]# head -2  access.log.1
     192.168.232.1 - - [16/Dec/2023:13:41:27 +0800] "GET / HTTP/1.1" 304 0 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36" "-"
     192.168.232.1 - - [16/Dec/2023:13:41:29 +0800] "GET / HTTP/1.1" 304 0 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36" "-"
    

    可以看出日志已经被轮转到新的文件中了,并创建了一个空的日志文件,其实日志是会被压缩的,不过要在下一次轮转的时候

    2)查看压缩效果

    日志文件已经是空的了,所以需要访问一下网页,产生一点日志,还需要把时钟时间修改一下

     logrotate -s /var/lib/logrotate/logrotate.status -f /etc/logrotate.d/nginx
    

    [root@localhost nginx]# ll
    -rw-r----- 1 nginx root 0 12月 21 00:00 access.log
    -rw-r----- 1 nginx root 20160 12月 19 00:15 access.log.1
    -rw-r----- 1 nginx root 344 12月 16 13:41 access.log.2.gz
    -rw-r–r-- 1 nginx root 0 12月 16 11:50 error.log

    可以看出新产生的日志已经被压缩了,error.log 没有被轮转的原因是它是一个空的文件

    5.4. 优化一下转储后得日志

    由于默认后缀是.1 .2 这样递增,意义不大,所以使用日期作为后缀

     [root@localhost nginx]# cat /etc/logrotate.d/nginx
     	/var/log/nginx/*.log {
        ......
         dateext       
     	......
     }
    

    注意日志文件不能为空,时间也要注意

     [root@localhost nginx]# ll
     -rw-r----- 1 nginx root  6144 12月 23 00:00 access.log
     -rw-r----- 1 nginx root 20160 12月 19 00:15 access.log.1
     -rw-r----- 1 nginx root   271 12月 23 00:00 access.log-20231223.gz
     -rw-r----- 1 nginx root   344 12月 16 13:41 access.log.2.gz
     -rw-r--r-- 1 nginx root     0 12月 16 11:50 error.log
    
  6. 定时执行轮转
    6.1. logrotate默认有加入到定时任务的,定时执行得脚本是 /etc/cron.daily/logrotate
    定时任务配置文件在

     /etc/anacrontab
    
    [root@localhost nginx]# cat  /etc/anacrontab
    # /etc/anacrontab: configuration file for anacron
    		
    # See anacron(8) and anacrontab(5) for details.
    		
    SHELL=/bin/sh
    PATH=/sbin:/bin:/usr/sbin:/usr/bin
    MAILTO=root
    # the maximal random delay added to the base delay of the jobs
    RANDOM_DELAY=45		// 最大随机廷迟
    # the jobs will be started during the following hours only
    START_HOURS_RANGE=3-22	// fanacron的执行时间范围是3:00~22:00
    		
    #period in days   delay in minutes   job-identifier   command
    1	5	cron.daily		nice run-parts /etc/cron.daily	// 每天开机 5 分钟后就检查 /etc/cron.daily 目录内的文件是否被执行,如果今天没有被执行,那就执行
    7	25	cron.weekly		nice run-parts /etc/cron.weekly		// 每天开机 5 分钟后就检查 /etc/cron.daily 目录内的文件是否被执行,如果今天没有被执行,那就执行
    @monthly 45	cron.monthly		nice run-parts /etc/cron.monthly		//每隔一个月开机后 45 分钟检查 /etc/cron.monthly 目录内的文件是否被执行,如果一个月内没有被执行,那就执行 
    

在这个文件中,"RANDOM_DELAY"定义的是最大随机延迟,也就是说,cron.daily 工作如果超过 1 天没有执行,则并不会马上执行,而是先延迟强制延迟时间,再延迟随机延迟时间,之后再执行命令;"START_HOURS_RANGE"的是定义 anacron 执行时间范围,anacron 只会在这个时间范围内执行。

6.2. 我们用 cron.daily 工作来说明一下 /etc/anacrontab 的执行过程:

  1. 读取 /var/spool/anacron/cron.daily 文件中 anacron 上一次执行的时间。
    和当前时间比较,如果两个时间的差值超过 1 天,就执行 cron.daily 工作。
  2. 只能在 03:00-22:00 执行这个工作。
    执行工作时强制延迟时间为 5 分钟,再随机延迟 0~45 分钟。
  3. 使用 nice 命令指定默认优先级,使用 run-parts 脚本执行 /etc/cron.daily 目录中所有的可执行文件。

大家会发现,/etc/cron.{daily,weekly,monthly} 目录中的脚本在当前的 Linux 中是被 anacron
调用的,不再依靠 cron 服务。不过,anacron 不用设置多余的配置,我们只需要把需要定时执行的脚本放入
/etc/cron.{daily,weekly,monthly} 目录中,就会每天、每周或每月执行,而且也不再需要启动 anacron
服务了。如果需要进行修改,则只需修改 /etc/anacrontab 配置文件即可

比如,我更加习惯让定时任务在凌晨 03:00-05:00 执行,就可以进行如下修改

[root@localhost nginx]# cat  /etc/anacrontab
# /etc/anacrontab: configuration file for anacron
	
	# See anacron(8) and anacrontab(5) for details.
	
	SHELL=/bin/sh
	PATH=/sbin:/bin:/usr/sbin:/usr/bin
	MAILTO=root
	# the maximal random delay added to the base delay of the jobs
	RANDOM_DELAY=0	// 把最大随机廷迟改为0分钟,不再随机廷迟
	# the jobs will be started during the following hours only
	START_HOURS_RANGE=3-5  // 执行时间范围为03:00—05:00
	
	#period in days   delay in minutes   job-identifier   command
	1	5	cron.daily		nice run-parts /etc/cron.daily
	7	25	cron.weekly		nice run-parts /etc/cron.weekly
	@monthly 0	cron.monthly		nice run-parts /etc/cron.monthly	// 把强制延迟也改为0分钟,不再强制廷迟

猜你喜欢

转载自blog.csdn.net/qq_50247813/article/details/135031308
今日推荐