logrotate 日志滚动的使用
2020-10-16 本文已影响0人
鸿乃江边鸟
最近由于最近上一个了项目,但是项目的本身没有做日志的滚动,导致日志一直在增长,这样下去肯定会撑爆磁盘,导致不可预测的结果
这个适合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.
正如man logrotate说的那样,logrotate可以实现自动轮替、压缩、删除日志、并且发邮件的功能
使用
root@49335c6e5ee3:/var/log# logrotate --help
Usage: 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 `/usr/bin/mail')
-s, --state=statefile Path of state file
-v, --verbose Display messages during rotation
-l, --log=STRING Log file or 'syslog' to log to syslog
--version Display version information
Help options:
-?, --help Show this help message
--usage Display brief usage message
也就是说,可以手动的执行 logrotate configfile 文件,那配置文件里的内容怎么设置呢,如下demo:
/var/log/cron.log {
daily
rotate 7
notifempty
create
size 1K
nocompress
nodateext
missingok
}
解释说明
参数 | 说明 |
---|---|
daily | 按天滚动 |
rotate | 保留的文件数量 |
notifempty | 如日志为空,则进行滚动 |
create | 旧日志文件轮替后创建新的日志文件 |
size | 日志达到多少进行日志滚动 |
nocompress | 日志文件不进行压缩 |
nodateext | 日志文件,以数字递增的形式增加,如:log.1 |
missingok | 假如日志文件不存在,不报错 |
具体的详细说明,参照man logrotate
运行机制
对安装了cron的系统来说,crontab会每天定时执行/etc/cron.daily目录下的脚本,而这个目录下有个文件叫logrotate :
#!/bin/sh
test -x /usr/sbin/logrotate || exit 0
/usr/sbin/logrotate /etc/logrotate.conf
我们看到 每天会运行/usr/sbin/logrotate /etc/logrotate.conf 这个命令,
在linux上 文件/etc/logrotate.conf内容如下:
# see "man logrotate" for details
# rotate log files weekly
weekly
# use the syslog group by default, since this is the owning group
# of /var/log/syslog.
su root syslog
# keep 4 weeks worth of backlogs
rotate 4
# create new (empty) log files after rotating old ones
create
# uncomment this if you want your log files compressed
#compress
# packages drop log rotation information into this directory
include /etc/logrotate.d
# no packages own wtmp, or btmp -- we'll rotate them here
/var/log/wtmp {
missingok
monthly
create 0664 root utmp
rotate 1
}
/var/log/btmp {
missingok
monthly
create 0660 root utmp
rotate 1
}
# system-specific logs may be configured here
我们看到include /etc/logrotate.d,会把/etc/logrotate.d目录下的文件include进来,
所以对于用户来说在/etc/logrotate.d 配置文件,就可以,总结一下
logrotate的配置文件:
/etc/logrotate.d/*
/etc/logrotate.conf