logrotate工具`
日志轮转特别适用于具有固定文件名的日志文件,比如MySQL的出错日志、常规查询日志、慢查询日志等。Linux系统有一个非常好用的根据logratate可以实现自动轮转,本文介绍它的原理和用法。
[mysql_3306 localhost.localdomain: mysql /data/mysql/my3306 ]
$ logrotate --help
用法: logrotate [OPTION...] <configfile>
-d, --debug Don't do anything, just test (implies -v)
-f, --force Force file rotation
-m, --mail=command Command to send mail (instead of `/bin/mail')
-s, --state=statefile Path of state file
-v, --verbose Display messages during rotation
-l, --log=STRING Log file
--version Display version information
Help options:
-?, --help Show this help message
--usage Display brief usage message
logrotate [-?dfv][-s <状态文件>][--usage][配置文件]
Linux系统默认安装logrotate工具,它默认的配置文件在:
/etc/logrotate.conf
/etc/logrotate.d/
创建MySQL root密码文件
vim /root/.my.cnf
[mysqladmin]
password = ncayu618
user= ncayu618
# 赋予600权限
chmod 600 /root/.my.cnf
给MySQL审计日志切割
# vim /etc/logrotate.d/audit.log-file
/data/mysql/my3306/data/audit.log {
notifempty
daily
dateext
rotate 7
compress
copytruncate
delaycompress
missingok
notifempty
create 644 mysql mysql
endscript
}
daily 指定rotate周期为每天,还有weekly, monthly。
rotate count 指定rotate日志文件保留的数量,如果没有配置这个参数,就不保留备份,设置1的话,就是保 留1个rotate备份,10就是保留10个rotate备份。
size size 当日志文件到达指定的大小时才转储,默认的大小单位是bytes,可以以k,M,G。比如size 10k, 10M, 10G。
compress 通过gzip压缩然后备份日志。
nocompress 默认值,不做gzip压缩处理。
delaycompress 和compress配合使用,rotate的日志文件到下一次执行logrotate时才进行压缩处理。
#copytruncate 把当前日志备份并截断,先拷贝原日志文件再清空,由于拷贝和清空之间有一个时间差,可能会丢失部 分日志数据。
create mode owner group rotate之后,创建新文件的日志文件并指定新文件的属性,比如:
create 644 tomcat tomcat
mail address 把rotate的日志文件发送到指定的E-mail。
dateext 使用当期日期作为命名格式,如果指定的rotate大于1,默认rotate之后的文件名是:xx.log.1, xx.log.2, xx.log3,如果配置dateext规则,那么rotate之后的文件名就会以日期结 尾:xx.log.2020-04-20,xx.log.2020-04-21, xx.log.2020-04-22
dateformat -%Y%m%d%H.%s 定义文件rotate后的文件名的日期格式,必须配合dateext使用,查了一下资料,目前只支持: %Y %m %d %H %s 这几个个参数(年,月,日,时,秒)
copytruncate 把当前日志备份并截断,先拷贝原日志文件再清空,由于拷贝和清空之间有一个时间差,可能会丢失部 分日志数据。
手动运行logrotate
#logrotate可以在任何时候从命令行手动调用。
logrotate -d /etc/logrotate.d/audit.log-file
###排障过程中的最佳选择是使用‘-d’选项以预演方式运行logrotate。要进行验证,不用实际轮循任何日志文件,可以模拟演练日志轮循并显示其输出。
-d:debug模式,就是先演练一遍,不是真干。
-f:强制模式,实打实的执行。
#设置定时任务
0 0 * * * /usr/sbin/logrotate -vf /etc/logrotate.d/audit.log-file