linux 27、 logrotate原理与使用

1 logrotate 基础


logrotate 程序是一个日志文件管理工具。用来把旧的日志文件删除,并创建新的日志文件,我们把它叫做“转储”。我们可以根据日志文件的大小,也可以根据其天数来转储,这个过程一般通过 cron 程序来执行。
logrotate 程序还可以用于压缩日志文件,以及发送日志到指定的E-mail 。


参考:
https://blog.csdn.net/cjwid/article/details/1690101

2 日志压缩配置


2.1 配置文件


/etc/logrotate.conf

2.2 配置内容


# see "man logrotate" for details
# rotate log files weekly
weekly

# keep 4 weeks worth of backlogs
rotate 4

# create new (empty) log files after rotating old ones
create
tabooext + .nodaily
compress
delaycompress
minsize 10M
maxsize 100M

# use date as a suffix of the rotated file
dateext
dateformat -%Y%m%d-%s

# uncomment this if you want your log files compressed
#compress

# RPM packages drop log rotation information into this directory
include /etc/logrotate.d

# no packages own wtmp and btmp -- we'll rotate them here
/var/log/wtmp {
    monthly
    create 0664 root utmp
        minsize 1M
    rotate 1
}

/var/log/btmp {
    missingok
    monthly
    create 0600 root utmp
    rotate 1
}

# system-specific logs may be also be configured here.


解释:
1) Logrotate是基于CRON来运行的,其脚本是「/etc/cron.daily/logrotate」
[root@node-2 ~]# ll /etc/cron.daily/logrotate
-rwx------. 1 root root 219 11月  6 2016 /etc/cron.daily/logrotate
[root@node-2 ~]# cat /etc/cron.daily/logrotate
#!/bin/sh

/usr/sbin/logrotate -s /var/lib/logrotate/logrotate.status /etc/logrotate.conf
EXITVALUE=$?
if [ $EXITVALUE != 0 ]; then
    /usr/bin/logger -t logrotate "ALERT exited abnormally with [$EXITVALUE]"
fi
exit 0

2) 实际运行时,Logrotate会调用配置文件「/etc/logrotate.conf」:

2.3 参数


参数    描述
compress    通过gzip 压缩转储以后的日志
delaycompress    一起使用时,转储的日志文件到下一次转储时才压缩
tabootext [+] list    让logrotate 不转储指定扩展名的文件,缺省的扩展名是:.rpm-orig, .rpmsave, v, 和 ~
size size    当日志文件到达指定的大小时才转储,后缀MB.

参考:
https://www.cnblogs.com/jianlibao/p/9996580.html


2.4 日志切割


比如以系统日志/var/log/message做切割来简单说明下:
第一次执行完rotate(轮转)之后,原本的messages会变成messages.1,而且会制造一个空的messages给系统来储存日志;
第二次执行之后,messages.1会变成messages.2,而messages会变成messages.1,又造成一个空的messages来储存日志!
如果仅设定保留三个日志(即轮转3次)的话,那么执行第三次时,则 messages.3这个档案就会被删除,并由后面的较新的保存日志所取代!也就是会保存最新的几个日志。
日志究竟轮换几次,这个是根据配置文件中的rotate参数来判定的。

weekly          //默认每一周执行一次rotate轮转工作
rotate 4       //保留多少个日志文件(轮转几次).默认保留四个.就是指定日志文件删除之前轮转的次数,0 指没有备份
create         //自动创建新的日志文件,新的日志文件具有和原来的文件相同的权限;因为日志被改名,因此要创建一个新的来继续存储之前的日志
dateext       //这个参数很重要!就是切割后的日志文件以当前日期为格式结尾,如xxx.log-20131216这样,如果注释掉,切割出来是按数字递增,即前面说的 xxx.log-1这种格式
compress      //是否通过gzip压缩转储以后的日志文件,如xxx.log-20131216.gz ;如果不需要压缩,注释掉就行
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

真实环境:
minsize 10M
maxsize 100M
解释:
minsize 1M #表示在轮替时间到达时 如果达到了最小size才发生轮替 比如 轮替时间时hourly 1个小时后 达到了1M就轮替 没达到就不轮替
maxsize 10M #表示不管是否到达轮替时间 只要大小超过10M 就发生轮替

真实环境的日志分割:
-rw-r--r-- 1 nova nova 2.8M 1月  11 03:11 nova-api.log-20190111-1547147462.gz
-rw-r--r-- 1 nova nova 2.8M 1月  12 03:16 nova-api.log-20190112-1547234161.gz
-rw-r--r-- 1 nova nova 2.9M 1月  13 03:26 nova-api.log-20190113-1547321162.gz
-rw-r--r-- 1 nova nova 1.8M 1月  13 18:30 nova-api.log-20190113-1547375401.gz
-rw-r--r-- 1 nova nova 3.9M 1月  15 03:30 nova-api.log-20190115-1547494201.gz
-rw-r--r-- 1 nova nova 2.8M 1月  16 03:30 nova-api.log-20190116-1547580602.gz
-rw-r--r-- 1 nova nova 2.8M 1月  17 03:25 nova-api.log-20190117-1547666701.gz


参考:
https://www.cnblogs.com/kevingrace/p/6307298.html
https://blog.csdn.net/liaomin416100569/article/details/78599529

3 如何重新更改日志分割系统并生效


3.1 将日志路径配置正确


具体到: /etc/logrotate.d/
下面找到自己写的日志分割文件
配置好正确的日志路径:
"/var/log/xxx/yyy.log"
注意:
请将上述xxx替换为对应的项目所在日志目录
请将上述yyy替换为对应的项目某个服务的日志文件名称

例如:
"/var/log/mongodb/mongod.log"


3.2 执行日志分割命令


查看现在地启动日志分割的命令是:
nice ionice -c3 /usr/sbin/logrotate /etc/logrotate.d/fuel.nodaily >& /tmp/logrotate

表示: cpu和磁盘调度都是在空闲状态情况下,才进行日志分割
>&: 表示复制一个文件描述符号, &>可以将错误信息或者普通信息都重定向输出。
    标准错误重定向到标准输出。
参考:
https://blog.csdn.net/qq_35242986/article/details/73772212
https://blog.csdn.net/sunfengye/article/details/78973831

解释:
1) man nice
作用:改变执行程序的优先级
总览 (SYNOPSIS)
       nice [OPTION]... [COMMAND [ARG]...]

描述 (DESCRIPTION)
       以  调整过的  调度优先级  运行  COMMAND.  如果  没给出 COMMAND, 就 显示
       当前的 优先级. ADJUST 缺省为 10, 范围 从 -20 (最高级) 到 19 (最低级).

       -ADJUST
              优先级 调整到 ADJUST

2) man ionice
作用: 影响磁盘调度的
格式: ionice -c class -p pid 
     ionice -c class -t COMMAND [ARG]
-c class: class表示调度策略,0 表示none, 1表示real-time,2表示best-effort,3表示idle
-p pid:指定要设置的进程号
-t: 忽视设置优先级产生的错误
COMMAND:表示命令名
参考:
http://linux.51yip.com/search/ionice


3.3 编写自己的日志分割的配置


实际运行时,Logrotate会调用配置文件「/etc/logrotate.conf」:
也可以在「/etc/logrotate.d」目录里放置自己的配置文件,用来覆盖Logrotate的缺省值。

现在我们自己编写了配置文件:
/etc/logrotate.d/fuel.nodaily
同时发现:
/etc/logrotate.d目录下面有
-rw-r--r--    1 root root     102 8月  10 2017 openstack-aodh
-rw-r--r--    1 root root     111 8月  10 2017 openstack-ceilometer
-rw-r--r--    1 root root     134 8月  10 2017 openstack-cinder
等目录

查看其他项目的日志分割配置
[root@node-2 logrotate.d]# cat openstack-ceilometer 
compress

/var/log/ceilometer/*.log {
    rotate 14
    size 10M
    missingok
    compress
    copytruncate
}

[root@node-2 logrotate.d]# cat openstack-aodh
compress

/var/log/aodh/*.log {
    weekly
    rotate 4
    missingok
    compress
    minsize 100k
}


参考:
https://linux.cn/article-4126-1.html
https://www.linuxidc.com/Linux/2017-02/140785.htm

3.4 查看logrotate的日志分割状态

 [root@node-2 logrotate.d]# cat  /var/lib/logrotate.status
logrotate state -- version 2
"/var/log/corosync.log" 2018-11-15-21:0:0
"/var/log/heat-all.log" 2019-1-13-6:30:1
"/var/log/syslog" 2018-11-15-21:0:0
"/var/log/nova/nova-compute.log" 2018-12-28-19:0:1
"/var/log/ceilometer/*.log" 2018-11-15-21:0:0
"/var/log/cinder/api.log" 2019-1-13-12:0:1
"/var/log/neutron-all.log" 2019-1-13-3:30:1

参考:
https://blog.csdn.net/looper66/article/details/58103470


4 自己编写日志分割的例子


4.1 新增一个mongodb的日志


在/etc/logrotate.d/ 目录下新建一个文件名为mongodb的文件,
该文件中写入如下内容

compress

/var/log/mongodb/*.log {
    rotate 10
    size 100M
    missingok
    compress
    copytruncate
}


4.2 执行日志分割命令


然后运行命令:
nice ionice -c3 /usr/sbin/logrotate  /etc/logrotate.d/mongodb >& /tmp/logrotate


注意:
请将 fuel.nodaily 替换为自己编写的日志分割配置

执行结果的样例如下:
[root@node-2 mongodb]# ll -h
-rw-r----- 1 mongod mongod    0 1月  19 13:45 mongod.log
-rw-r----- 1 mongod mongod 444K 1月  19 13:30 mongod.log-20190119-1547875801.gz
-rw-r----- 1 mongod mongod 444K 1月  19 13:33 mongod.log-20190119-1547876003.gz
-rw-r----- 1 mongod mongod 149M 1月  19 13:45 mongod.log-20190119-1547876741

-rw-r----- 1 mongod mongod 444K 1月  19 13:30 mongod.log-20190119-1547875801.gz
-rw-r----- 1 mongod mongod 444K 1月  19 13:33 mongod.log-20190119-1547876003.gz
-rw-r----- 1 mongod mongod 444K 1月  19 13:45 mongod.log-20190119-1547876741.gz
-rw-r--r-- 1 root   root   149M 1月  19 13:49 mongod.log-20190119-1547876953

验证ok。


4.3 调试日志分割


logrotate -d /etc/logrotate.d/mongodb

注意:
请将 fuel.nodaily 替换为自己编写的日志分割配置

调试结果如下:
compressing log with: /bin/gzip
copying /var/log/mongodb/mongod.log to /var/log/mongodb/mongod.log-20190119-1547876639
truncating /var/log/mongodb/mongod.log
running postrotate script
running script with arg /var/log/mongodb/mongod.log: "
      /bin/kill -HUP `cat /var/run/syslogd.pid 2> /dev/null` 2> /dev/null || true
      reload rsyslog >/dev/null 2>&1 || true
"

可以看到,调试日志中已经对mongodb的日志进行处理了。

5 logrotate原理


为什么只要将 logrotate配置文件放在logrotate.d下面就会自动执行?
执行:
man logrotate
可以看到:
Normally, logrotate is run as a daily cron job,表示logrotate一般是以一个cron job的形式每天执行,而cron的每天任务是放在/etc/cron.daily目录下的,查看该目录:

[root@node-2 cron.daily]# ll /etc/cron.daily 
总用量 12
-rwx------. 1 root root 219 11月  6 2016 logrotate
-rwxr-xr-x. 1 root root 618 3月  18 2014 man-db.cron
-rwx------. 1 root root 208 11月  5 2016 mlocate

查看logrotate,内容如下:
[root@node-2 cron.daily]# cat /etc/cron.daily/logrotate 
#!/bin/sh

/usr/sbin/logrotate -s /var/lib/logrotate/logrotate.status /etc/logrotate.conf
EXITVALUE=$?
if [ $EXITVALUE != 0 ]; then
    /usr/bin/logger -t logrotate "ALERT exited abnormally with [$EXITVALUE]"
fi
exit 0

分析:
重点是:
/usr/sbin/logrotate -s /var/lib/logrotate/logrotate.status /etc/logrotate.conf

查看:
/etc/logrotate.conf
内容如下:
# see "man logrotate" for details
# rotate log files weekly
weekly

# keep 4 weeks worth of backlogs
rotate 4

# create new (empty) log files after rotating old ones
create
tabooext + .nodaily
compress
delaycompress
minsize 10M
maxsize 100M

# use date as a suffix of the rotated file
dateext
dateformat -%Y%m%d-%s

# uncomment this if you want your log files compressed
#compress

# RPM packages drop log rotation information into this directory
include /etc/logrotate.d

# no packages own wtmp and btmp -- we'll rotate them here
/var/log/wtmp {
    monthly
    create 0664 root utmp
    minsize 1M
    rotate 1
}

/var/log/btmp {
    missingok
    monthly
    create 0600 root utmp
    rotate 1
}

# system-specific logs may be also be configured here.

分析:
重点在 include /etc/logrotate.d
分析这个目录,具体如下所示:

[root@node-2 cron.daily]# cd  /etc/logrotate.d
[root@node-2 logrotate.d]# ls
ceph          httpd           libvirtd.qemu   openstack-ceilometer  openstack-keystone  openstack-sahara  rabbitmq-server  wpa_supplicant
chakra        influxdb        mariadb         openstack-cinder      openstack-magnum    openstack-trove   samba            yum
chrony        influxdb-relay  murano          openstack-glance      openstack-manila    openvswitch       skynet           zabbix-agent
fuel.nodaily  iscsiuiolog     numad           openstack-heat        openstack-neutron   ppp               syslog           zabbix-server
haproxy       libvirtd        openstack-aodh  openstack-ironic      openstack-nova      puppet            telegraf

可以看到,/etc/logrotate.d下包含了各个组件的日志分割的配置文件。
这就解释了为什么在:
/etc/logrotate.d 下面新增一个配置文件就可以被logrotate执行了。

至于,为什么cron.daily如何被调用,请看下面分析:
man cron
看到如下内容:
 Cron also searches for /etc/anacrontab and any files in the /etc/cron.d directory, which have a different  format  (see  crontab(5)).
       Cron  examines  all  stored  crontabs and checks each job to see if it needs to be run in the current minute.  When executing commands, any
       output is mailed to the owner of the crontab (or to the user specified in the MAILTO environment variable in the crontab, if such  exists).
       Any job output can also be sent to syslog by using the -s option.

       Cron checks these files and directories:

       /etc/crontab
              system  crontab.   Nowadays  the  file  is empty by default.  Originally it was usually used to run daily, weekly, monthly jobs.  By
              default these jobs are now run through anacron which reads /etc/anacrontab configuration file.  See anacrontab(5) for more details.

       /etc/cron.d/
              directory that contains system cronjobs stored for different users.

分析:
cron默认会读取/etc/crontab和/etc/cron.d下面的文件,但是现在会读取
/etc/anacrontab这个配置文件进行处理。

查看/etc/crontab:
[root@node-2 logrotate.d]# cat /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

查看:
man anacron

       Anacron reads a list of jobs from the  /etc/anacrontab  configuration  file  (see  anacrontab(5)).
       This  file  contains the list of jobs that Anacron controls.  Each job entry specifies a period in
       days, a delay in minutes, a unique job identifier, and a shell command.
分析:
anacron的默认配置文件为/etc/anacrontab

[root@node-2 cron.d]# cat /etc/anacrontab
# /etc/anacrontab: configuration file for anacron
# managed by puppet
# 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=25
# the jobs will be started during the following hours only
START_HOURS_RANGE=3-22

#period in days   delay in minutes   job-identifier   command
1                 5                  cron.daily       nice ionice -c3 run-parts /etc/cron.daily
7                 25                 cron.weekly      nice ionice -c3 run-parts /etc/cron.weekly
@monthly          45                 cron.monthly     nice ionice -c3 run-parts /etc/cron.monthly

分析:
其中 #period in days 下面的1 表示一天执行一次,5表示延迟5分钟

那anacron又是何时执行呢?上文在讲cron默认读取的文件时,除了/etc/crontab之外,还会读取/etc/cron.d/下的文件,将该目录列出:
查看:
ll /etc/cron.d 

上面说anacron不是一个后台进程,开机自启的目的是为了把遗漏的任务给补上,运行完任务后就退出了,在本次开机后的下一次执行任务就要由cron来编排了,这么说就清楚了. 那么logrotate配置文件的执行时间就是开机时间+延时时间或者7:30加延时时间.

总结logrotate运行时间:
具体什么时候执行呢? 如果 anacron有安装,则在刚开机时如果条件满足则是 开机时间+延时时间,如果是已经开机后条件满足则是 /etc/cron.d/anacron中编排的时间+延时时间;如果没有安装,则时间为 /etc/crontab中编排的时间. 
注:

参考:
https://www.aliyun.com/jiaocheng/118904.html


整理后的参考:
[1] https://blog.csdn.net/cjwid/article/details/1690101
[2] https://www.cnblogs.com/jianlibao/p/9996580.html
[3] https://www.cnblogs.com/kevingrace/p/6307298.html
[4] https://blog.csdn.net/liaomin416100569/article/details/78599529
[5] https://blog.csdn.net/qq_35242986/article/details/73772212
[6] https://blog.csdn.net/sunfengye/article/details/78973831
[7] http://linux.51yip.com/search/ionice
[8] https://linux.cn/article-4126-1.html
[9] https://www.linuxidc.com/Linux/2017-02/140785.htm
[10] https://blog.csdn.net/looper66/article/details/58103470
[11] https://www.aliyun.com/jiaocheng/118904.html
 

猜你喜欢

转载自blog.csdn.net/qingyuanluofeng/article/details/86654022
27
今日推荐