欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 房产 > 家装 > 日志轮转—cron和logrotate

日志轮转—cron和logrotate

2024/10/24 3:26:50 来源:https://blog.csdn.net/Sheng_Q/article/details/139877824  浏览:    关键词:日志轮转—cron和logrotate

背景

本文介绍如何基于linux系统的cron和logrotate实现日志轮转。cron是一个定时任务管理器,根据配置定时触发任务;logrotate是一个日志轮转工具,根据配置处理日志,logrotate依赖于cron的定时触发。

1.cron

cron是linux系统自带的执行定时任务的工具。cron有3个概念需要区分:cron代表这个软件,crond代表实际运行的进程,crontab用于修改配置文件的客户端工具。cron的核心是配置文件,crond每分钟会读取并比较配置文件时间戳,以确认是否有修改。 该过程是一个热部署,即修改cron配置文件不需要重启crond服务。

1.1 crond服务

crond服务由systemd进行管理,可以参考相关内容, 即可通过systemctl命令查看和启停crond服务:

#停止crond
systemctl stop crond#运行crond
systemctl start/restart crond#查看crond状态
systemctl status crond

service文件路径为:/usr/lib/systemd/system/crond.service,文件内容如下:

[Unit]
Description=Command Scheduler
After=auditd.service systemd-user-sessions.service time-sync.target[Service]
EnvironmentFile=/etc/sysconfig/crond
ExecStart=/usr/sbin/crond -n $CRONDARGS
ExecReload=/bin/kill -HUP $MAINPID
KillMode=process
Restart=on-failure
RestartSec=30s[Install]
WantedBy=multi-user.target

通过/usr/sbin/crond -n $CRONDARGS指令启动crond进程。

除了使用linux的systemctl管理crond外,可以手动在命令行中以调试模式打开,如下所示:

[root@host44 ~]# crond -x test
debug flags enabled: test
[3327] cron started
log_it: (CRON 3327) INFO (RANDOM_DELAY will be scaled with factor 0% if used.)
log_it: (CRON 3327) INFO (running with inotify support)
log_it: (CRON 3327) INFO (@reboot jobs will be run at computer's startup.)
...

注意:一个系统中只能运行一个crond程序,通过进程文件/var/run/crond.pid锁住。因此,执行crond -x test需要执行service crond stop闭系统管理的crond。

一般情况下不使用调试模式,可以通过crond日志文件查看执行记录。文件路径为/var/log/cron,记录了定时任务的日志调度记录,包含时间和执行内容,如:

Jun 21 09:29:01 host44 CROND[27228]: (root) CMD (/usr/sbin/logrotate  /etc/logrotate.d/sfums.logrotate)

1.2 crond配置格式

cron读取配置文件后,会根据配置信息执行任务,格式如下所示:

${minute}  ${hour}  ${day}  ${month}  ${week} ${user-name}  ${command to be executed}

其中,minute的取值范围:0 - 59;hour的取值范围: 0-23;day的取值范围: 1-31;month的取值范围: 1-12,week的取值范围:0-7(0和7表示周日).
另外,可用通配符和特殊字符进行配置:常见的有逗号(,)、星号(*)、斜线(/),其中 ,表示枚举, *表示每, /表示增量。

#在每天的1点、3点和5点的第5分钟,以root用户的身份执行(/usr/bin/echo 'hello' >> log.txt)这个命令
5 1,3,5 * * * root /usr/bin/echo 'hello' >> log.txt#每5分钟执行一次指令
*/5 * * * * root /usr/bin/echo 'hello' >> log.txt

与Java中使用的cron表达式类似,本文不进行展开介绍。

1.3 cron配置文件

cron根据用户和执行频率不同,有不同的配置文件路径。

[root@124 etc]# ls -al /etc | grep cron
-rw-r--r--.   1 root root      451 610 2014 crontab
drwxr-xr-x.   2 root root       70 621 14:25 cron.d
drwxr-xr-x.   2 root root       57 621 08:57 cron.daily
drwxr-xr-x.   2 root root       22 621 08:59 cron.hourly
drwxr-xr-x.   2 root root        6 610 2014 cron.monthly
drwxr-xr-x.   2 root root        6 610 2014 cron.weekly

按照章节1-2中格式的定时任务配置完成后,可以写入/etc/crontab文件中,或者单独作为文件放在/etc/cron.d文件夹下。

[root@host44 cron.d]# cat /etc/cron.d/testEwen
*/1 * * * * root /usr/bin/echo "test" >> /test/testEwen.log

同时cron定制了几个特殊的场景,每时/天/周/月,将任务文件放到对应的路径即可。对于每天执行一次的任务,需要将配置文件放到/etc/cron.daily文件夹,如/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

crond每天会执行一次logrotate脚本。

说明:以上配置建议用于系统级的定时任务,用户级别的定时任务可在/var/spool/cron/路径下配置,每个用户对应一个文件;如ewen用户对应/var/spool/cron/ewen文件。

1.4 crontab客户端

crontab常用的操作由查询和修改配置。
[1] 使用crontab -l查询当前用户的定时任务配置:

[root@124 cron.d]# crontab -l
*/1 *  * * * /usr/bin/ls >> /test/test1.log

[2] 使用crontab -e修改当前用户的定时任务配置,相当于使用vim打开了/var/spool/cron/用户名文件。

2.logrotate

logrotate为日志管理工具,通过配置,可以实现自动轮转、压缩、删除和邮件日志文件。从而可以避免日志文件无限制地增长,导致耗尽磁盘空间。logrotate的实现依赖于crond服务,即logrotate的每次执行由cron触发。因此,可以从cron的配置中找到logrotate,如下所示:

[root@124 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

由此,crond每天会执行一次/usr/sbin/logrotate -s /var/lib/logrotate/logrotate.status /etc/logrotate.conf指令。
其中:-s /var/lib/logrotate/logrotate.status用于指定日志轮转的状态文件,用于记录文件轮转时间;/etc/logrotate.conf是logrotate的配置文件。/etc/logrotate.conf中核心配置项是include /etc/logrotate.d , 即该配置文件将加载/etc/logrotate.d目录下所有的配置文件,用户可将自己的配置放在该目录下。

2.1 配置文件

logrotate的配置文件格式为文件 {配置信息},可在一个文件中为多个文件配置,如下所示:

/var/log/nginx/*.log {  daily  rotate 7  compress  delaycompress  missingok  notifempty  create 0640 www-data adm  sharedscripts  postrotate  /etc/init.d/nginx reload > /dev/null  endscript  
}

此时配置对/var/log/nginx/路径下所有文件名以log结尾的文件生效。以下对各配置项分别进行介绍:
[1] 日志轮转方式
copytruncate 推荐设置,将日志文件复制后,对原日志文件进行截断(相当于执行>xx.log,情况原日志文件),此时应用程序可以继续写入日志,但截断过程中,可能有数据丢失;
nocopytruncate 不推荐,移动或者重命名日志文件(相当于mv),而不进行日志文件的截断,此时程序可能因无法找到日志文件而报错。

[2] 轮转周期
指定日志轮转的周期,可配置为: daily, weekly, monthly, yearly,分别表示每天一次、每周一次、每月一次和每年一次。

[3] size
指定日志轮转的阈值,当日志文件达到指定大小时才轮转。如size 100M表示日志文件超过100M时触发。

[4] 日志格式
dateext和dateformat参数用于控制备份日志文件的命名方式。不进行配置是,logrotate使用logfile.log.1、logfile.log.2等递增的数组后缀方式命名备份的日志文件。
启用dateext后,添加日期作为扩展名;
dateformat用于自定义日期格式,与dateext配置使用,可以使用%Y(年)、%m(月)、%d(日期)和%s(秒)这四个参数。如:

dateext
dateformat %Y%m%d  

此时,日志格式为logfile.log-20240622。另外,如果不指定dateformat,logrotate通常会使用默认的日期格式(通常是YYYY-MM-DD)。

[5] rotate
保留日志备份的数量,如rotate 5表死会保留最近的5个轮转的日志备份。

[6] 为空是否轮转
ifempty 日志文件为空,也轮转; notifempty 日志文件为空,不轮转。

[7] missingok
如果日志文件丢失,不报错继续执行。

[8] 压缩
compress表示使用gzip压缩轮转后的日志文件;nocompress表示不进行压缩;
delaycompress延迟压缩,下次轮转时才压缩当前轮转的日志文件;nodelaycompress日志轮转时立刻压缩。

[9] create mode owner group
配置轮转日志的属组,设置轮转日志文件的权限和属组,如:create 755 ewen ewen; nocreate表示日志轮转后,不创建新的日志文件。
[10] 轮转触发
prerotate/endscript用于日志轮转前触发:

prerotate// 	操作指令
endscript

postrotate/endscript用于日志轮转后触发:

postrotate// 	操作指令
endscript

2.2 logrotate指令

logrotate [options] <configfile>
常用选项包括:
–force:强制进行日志文件的轮转,即使未达到轮转条件;
–verbose:输出执行过程的详细信息;
–debug:输出debug调试信息;
configfile为logrotate配置文件;初次之外,还可以通过 -s指定status状态文件,status状态文件中保存了每个日志轮转的时间戳。
以下通过简单案例介绍logrotate的使用方式。
准备日志文件

# 创建空的日志文件
touch /test/a.log
echo 12345678 >>/test/a.log

准备logrotate配置文件

# test.conf
/test/*.log {copytruncatesize 10  rotate 7  compresscreate
}

准备logrotate的status文件

touch /test/logrotate.status

执行logroate进行日志轮转

cd /testlogrotate -s logrotate.status test.conf

此时,日志并未进行轮转,如下所示:

[root@VM-4-6-centos nginx]# ls -al
-rw-r--r--  1 root root    9 622 15:59 a.log
-rw-r--r--  1 root root   67 622 15:58 test.conf
-rw-r--r--  1 root root   72 622 16:03 logrotate.status

分析:
由于a.log的大小为9个字节,而logrotate.conf中通过size设置轮转条件为10字节,因此未轮转;可通过 --debug查看详细信息:

[root@VM-4-6-centos nginx]# logrotate -s logrotate.status test.conf --debug
reading config file logrotate.conf
Allocating hash table for state file, size 15360 BHandling 1 logsrotating pattern: /test/a.log 10 bytes (7 rotations)
empty log files are rotated, old logs are removed
considering log /test/a.loglog does not need rotating (log size is below the 'size' threshold)

可通过-f或者–force强制进行日志轮转:

logrotate -s logrotate.status -f  logrotate.conf

查看轮转情况:

[root@VM-4-6-centos nginx]# ll
-rw-r--r-- 1 root root  0 622 16:17 a.log
-rw-r--r-- 1 root root  0 622 16:17 a.log.1
-rw-r--r-- 1 root root 67 622 15:58 logrotate.conf
-rw-r--r-- 1 root root 74 622 16:17 logrotate.status[root@VM-4-6-centos nginx]# cat logrotate.status 
"/test/a.log" 2024-6-22-16:17:27

2.3 logrotate搭配cron运行

章节1.3 cron配置文件可知,crond每天会执行一次/etc/cron.daily/logrotate脚本,该脚本中会触发日志轮转:

/usr/sbin/logrotate -s /var/lib/logrotate/logrotate.status /etc/logrotate.conf

/etc/logrotate.conf配置文件通过include /etc/logrotate.d加载了 /etc/logrotate.d目录下的配置,即将test.conf放在 /etc/logrotate.d路径下即可实现每天触发一次。

3.案例介绍

基于章节1章节2的介绍,以下根据不同业务场景抽象出三个案例。

3.1 每周触发一次调度

将test.conf文件放在/etc/logrotate.d路径下,test.conf配置文件如下所示:

# test.conf
/test/*.log {copytruncateweeklyrotate 7  compresscreate
}

3.2 每天触发,日志文件达到100M触发

将test.conf文件放在/etc/logrotate.d路径下,test.conf配置文件如下所示:

# test.conf
/test/*.log {copytruncatesize 100Mrotate 7  compresscreate
}

3.3 每周触发一次,如果超过100M才触发

准备logrotate配置文件:
将test.conf文件放在/test路径下,test.conf配置文件如下所示:

# test.conf
/test/*.log {copytruncatesize 100Mrotate 7  compresscreate
}

为crond添加配置文件:
在/etc/cron.weekly目录下添加配置文件test, 配置内容如下:

/usr/sbin/logrotate -s /var/lib/logrotate/logrotate.status /test/test.conf

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com