1. 安装
logrotate 是一个 Linux系统日志的管理工具。可以对单个日志文件或者某个目录下的文件按时间 / 大小进行切割,压缩操作;指定日志保存数量;还可以在切割之后运行自定义命令。
logrotate 是基于 crontab 运行的,所以这个时间点是由 crontab 控制的
主流 Linux 发行版上都默认安装有 logrotate 包,如果你的 Linux 系统中找不到 logrotate, 可以使用 apt-get 或 yum 命令来安装。
yum install -y logrotate
一般 Linux 都已经自带 logrotate,下列命令可以查看是否已安装。
rpm -ql logrotate
2. 入门
/etc/logrotate.conf 这个文件是 logrotate 的主配置文件。
# 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
# use date as a suffix of the rotated file
dateext
# uncomment this if you want your log files compressed
#compress
# 包含自定义配置目录
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 表示其会加载 /etc/logrotate.d 的所有自定义配置文件,自定义配置文件中的配置可以覆盖掉通用配置。
我们来到自定义配置文件的目录/etc/logrotate.d/:
vim nginx
/var/log/nginx/*.log {
create 0640 nginx root
daily # 按天切割
rotate 10 # 对于同一个日志文件切割后最多保留的文件个数
missingok # 切割中遇到日志错误忽略
notifempty # 当日志文件为空时不分割
compress # 以gzip方式压缩
delaycompress # 分割后对最新的序号为1的文件不会进行压缩,对其他序号的文件进行压缩,这样可以方便我们查看最新的分割日志
sharedscripts # 所有的文件切割之后只执行一次下面脚本,通知nginx重新打开新的日志文件进行后续写入
postrotate
/bin/kill -USR1 `cat /run/nginx.pid 2>/dev/null` 2>/dev/null || true # 通过USER1信号通知nginx重新打开日志文件
endscript
}
适用于其它程序日志分隔:如redis等
/var/log/redis/*.log {
weekly
rotate 10
copytruncate
delaycompress
compress
notifempty
missingok
}
3. logrotate命令
logrotate 命令格式:
logrotate [OPTION...] <configfile>
-d, --debug :debug模式,测试配置文件是否有错误。
-f, --force :强制转储文件。
-m, --mail=command :压缩日志后,发送日志到指定邮箱。
-s, --state=statefile :使用指定的状态文件。
-v, --verbose :显示转储过程。
手动执行,检测配置是否可用:
logrotate -vf /etc/logrotate.d/nginx