Linux 日志分割神器 logrotate

文章
林里克斯

logrotate 是管理系统所产生的记录文件,它提供自动替换,压缩,删除和邮寄记录文件,每个记录文件都可被设置成每日,每周或每月处理,也能在文件太大时立即处理。

实验平台:CentOS 7.7.1908

logrotate version : 3.8.6


一、介绍和安装


1.GitHub

https://github.com/logrotate/logrotate
  1. CentOS 都是预安装了此命令
$ rpm -qa | grep logrotate
logrotate-3.8.6-19.el7.aarch64

3.参数详情

$ logrotate --help
Usage: logrotate [OPTION...] <configfile>
  -d, --debug               #详细显示指令执行过程,便于排错或了解程序执行的情况
  -f, --force               #强行启动记录文件维护操作,纵使 logrotate 指令认为没有需要亦然
  -m, --mail=command        #发送邮件的命令(而不是“/bin/mail”)
  -s, --state=statefile     #使用指定的状态文件
  -v, --verbose             #显示指令执行过程
  -l, --log=STRING          #指定日志文件
  --version                 #查看版本号

Help options:
  -?, --help                #查看帮助信息
  --usage                   #显示指令基本用法

4.logrotate 目录

/etc/logrotate.conf
#默认配置文件路径
/etc/logrotate.d/
独立配置文件路径

5.logrotate.conf 配置参数

daily           #指定转储周期为每天
weekly          #指定转储周期为每周
monthly         #指定转储周期为每月

rotate count    #指定日志文件删除之前转储的个数,0 指没有备份,4 指保留 4 个备份

compress        #通过 gzip 压缩转储以后的日志
nocompress      #不适用压缩
delaycompress   #和 compress 一起使用时,转储的日志文件到下一次转储时才压缩
nodelaycompress #覆盖 delaycompress 选项,转储同时压缩

copytruncate    #用于还在打开中的日志文件,把当前日志备份并截断;是先拷贝再清空的方式,拷贝和清空之间有一个时间差,可能会丢失部分日志数据。
nocopytruncate  #备份日志文件但是不截断

create mode owner group #转储文件,使用指定的文件模式创建新的日志文件。轮转时指定创建新文件的属性,如 create 644 root root
nocreate        #不建立新的日志文件

errors address  #转储时的错误信息发送到指定的Email 地址
mail address    #把转储的日志文件发送到指定的E-mail 地址

ifempty         #即使是空文件也转储,这个是 logrotate 的缺省选项
notifempty      #如果是空文件的话,不转储

olddir directory    #转储后的日志文件放入指定的目录,必须和当前日志文件在同一个文件系统
noolddir        #转储后的日志文件和当前日志文件放在同一个目录下

prerotate/endscript     #在 logrotate 转储之前需要执行的指令,例如修改文件的属性等动作;这两个关键字必须单独成行;
postrotate/endscript    #在 logrotate 转储之后需要执行的指令,例如重新启动 (kill -HUP) 某个服务!必须独立成行;

tabootext [+] list 让logrotate   #不转储指定扩展名的文件,缺省的扩展名是:.rpm-orig, .rpmsave, v, 和 ~ 

size            #当日志文件到达指定的大小时才转储,size 可以指定 bytes (缺省)以及 KB (sizek)或者 MB (sizem).

missingok       #如果日志丢失,不报错继续滚动下一个日志

notifempty      #当日志文件为空时,不进行轮转

sharedscripts   #运行 postrotate 脚本,作用是在所有日志都轮转后统一执行一次脚本。如果没有配置这个,那么每个日志轮转后都会执行一次脚本

dateext         #使用当期日期作为命名格式
dateformat .%s  #配合 dateext 使用,紧跟在下一行出现,定义文件切割后的文件名,必须配合 dateext 使用,只支持 %Y %m %d %s 这四个参数

dateyesterday   #切割后的文件日志命名为昨天的日期

6.切割时间

logrotate 按时间切割有 天|周|月|,可具体时间是几点钟?logrotate 默认的定时任务放在了 /etc/cron.daily/logrotate 文件中

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 logotate 的命令,然后下面有一个判断执行是否成功,并没有时间,这该去哪里找?logrotate 的行为也是受 crontab 控制,而 crontab 任务是手 anacron 控制,所以来看 anacrontab

$ 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          

#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 45    cron.monthly        nice run-parts /etc/cron.monthly
#所有系统级别的计划任务都是在上面脚本 START_HOURS_RANGE= 指定的时间点内执行,3-22 表示每天的凌晨 3点-22点内,随机执行
#我们可以修改 START_HOURS_RANGE= 23-24 (这是日志切割时间点,即只在23点到24点开始切割)

7.自己写 crontab 任务来执行切割

$ rm -rf /etc/cron.daily/logrotate
#删除自带任务计划
$ crontab -e
00 00 * * * /sbin/logrotate -f /etc/logrotate.d/nginx

二、实操案例


1.Nginx

$ vim /etc/logrotate.d/nginx

/usr/local/nginx/logs/*.log {
        daily
        rotate 7
        missingok
        notifempty
        compress
        nodelaycompress
        copytruncate
        create 644 nginx nginx
        dateext
        dateformat -%Y-%m-%d
        dateyesterday
}

2.手动执行切割(做测试使用)

写入 30M 内容

$ head -c 30M < /dev/urandom > /usr/local/nginx/logs/error.log 
$ head -c 30M < /dev/urandom > /usr/local/nginx/logs/access.log

3.强制执行切割(不管是否到了任务计划自动执行时间)

$ logrotate -vf /etc/logrotate.d/nginx 
reading config file /etc/logrotate.d/nginx
Allocating hash table for state file, size 14336 B

Handling 1 logs

rotating pattern: /usr/local/nginx/logs/*.log  forced from command line (7 rotations)
empty log files are not rotated, old logs are removed
considering log /usr/local/nginx/logs/access.log
  log needs rotating
considering log /usr/local/nginx/logs/error.log
  log needs rotating
rotating log /usr/local/nginx/logs/access.log, log->rotateCount is 7
Converted ' -%Y-%m-%d' -> '-%Y-%m-%d'
dateext suffix '-2020-09-03'
glob pattern '-[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]'
glob finding old rotated logs failed
copying /usr/local/nginx/logs/access.log to /usr/local/nginx/logs/access.log-2020-09-03
truncating /usr/local/nginx/logs/access.log
compressing log with: /bin/gzip
rotating log /usr/local/nginx/logs/error.log, log->rotateCount is 7
Converted ' -%Y-%m-%d' -> '-%Y-%m-%d'
dateext suffix '-2020-09-03'
glob pattern '-[0-9][0-9][0-9][0-9]-[0-9][0-9]-[0-9][0-9]'
glob finding old rotated logs failed
copying /usr/local/nginx/logs/error.log to /usr/local/nginx/logs/error.log-2020-09-03
truncating /usr/local/nginx/logs/error.log
compressing log with: /bin/gzip

4.查看切割的效果

$ ls -lh /usr/local/nginx/logs/
total 61M
-rw-r--r-- 1 nginx nginx   0 Sep  4 15:13 access.log
-rw-r--r-- 1 nginx nginx 31M Sep  4 15:12 access.log-2020-09-03.gz
-rw-r--r-- 1 nginx nginx   0 Sep  4 15:14 error.log
-rw-r--r-- 1 nginx nginx 31M Sep  4 15:12 error.log-2020-09-03.gz

5.查看已切割日志

zcat /usr/local/nginx/logs/error.log-2020-09-03.gz

6.案例二(向 Nginx 发送信号重新打开日志文件切割)

$ vim /etc/logrotate.d/nginx
/usr/local/nginx/logs/*.log {
        daily
        rotate 30
        missingok
        notifempty
        compress
        nodelaycompress
        dateext
        dateformat -%Y-%m-%d
        dateyesterday
        postrotate
            if [ -f /usr/local/nginx/run/nginx.pid ];then
                kill -USR1 `cat /usr/local/nginx/run/nginx.pid`
            fi
        endscript
}
#在切割后执行 postrotate / endscript 之间的命令,向nginx发送信号重新打开日志

Over~

版权协议须知!

本篇文章来源于 Uambiguous ,如本文章侵犯到任何版权问题,请立即告知本站,本站将及时予与删除并致以最深的歉意

739 0 2020-09-04


分享:
icon_mrgreen.gificon_neutral.gificon_twisted.gificon_arrow.gificon_eek.gificon_smile.gificon_confused.gificon_cool.gificon_evil.gificon_biggrin.gificon_idea.gificon_redface.gificon_razz.gificon_rolleyes.gificon_wink.gificon_cry.gificon_surprised.gificon_lol.gificon_mad.gificon_sad.gificon_exclaim.gificon_question.gif
博主卡片
林里克斯 博主大人
一个致力于Linux的运维平台
运维时间
搭建这个平台,只为分享及记载自己所遇之事和难题。

现在时间 2024-04-26

今日天气
站点统计
  • 文章总数:240篇
  • 分类总数:29个
  • 评论总数:10条
  • 本站总访问量 215861 次

@奥奥

@Wong arrhenius 牛比

@MakerFace 厉害了!