====== logrotate ====== [[https://linux.die.net/man/8/logrotate|logrotate]] is designed to ease administration of systems that generate large numbers of log files. It allows automatic rotation, compression, removal, and mailing of log files. Each log file may be handled daily, weekly, monthly, or when it grows too large. logrotate 基于 [[linux:crontab|crontab]] 来运行,运行脚本放在 ''/etc/cron.daily/logrotate'' 中,每日执行。 ===== Configuration ===== 配置文件位于 ''/etc/logrotate.conf'',centos 的默认配置如下: # 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 # 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 } ==== Directives ==== 下面对一些常用的指令进行说明 === 基础 === **compress**:日志将会使用 ''gzip'' 压缩,''nocompess'' 相反 **copytruncate**:复制原有日志,并将原有日志文件尺寸 truncate 至 0 。该功能可解决一些程序仍然往旧日志写入新日志内容的问题。 **create [mode owner group], create [owner group]** :日志创建权限 **ifempty**: 即使日志为空,仍然 Rotate 日志,''notifempty'' 相反 **missingok**:日志不存在时不报告错误 **rotate**:rotate 保留份数,默认为 0,当值为 0 时,旧日志将会被删除 **size [size]**:当文件大小超过 ''[size]'' 时才 rotate 日志。''size'' 格式为 100k, 100M, 100G === 格式 === **dateext**:存档时使用 ''YYYYMMDD'' 后缀而不是添加数字 === 频率 === **daily**:每天 ''rotate'' 日志一次 **hourly**:每小时 ''rotate'' 日志一次,用户需要将 ''logrotate'' cron 改为每小时运行 **weekly [weekday]**:每 ''weekday'' 执行 ''rotate'' 日志一次,0 为星期天,1 为星期一,如此类推,7 为每 7 天运行一次,无视 ''weekday'' **monthly**:每个月 ''rotate'' 日志一次,一般在每月的第一天 ===== Usage ===== 以下以 nginx 的 logrotate 配置文件来说明常用的用法。 /var/log/nginx/*.log { daily # 每天备份一次 copytruncate missingok rotate 60 # 保留60份日志 compress delaycompress # 除了第一份以外,其余日志都压缩 notifempty # 日志文件为空时,不执行 create 640 nginx adm # 创建日志文件的权限 dateext } ===== Reference ===== * [[https://linux.die.net/man/8/logrotate|logrotate(8) man]] * [[https://huoding.com/2013/04/21/246|被遗忘的Logrotate]] * [[https://linux.cn/article-4126-1.html|Linux日志文件总管——logrotate]]