logrotate 日志滚动的使用

logrotate是一款用于管理大量日志文件的工具,它可以自动轮换、压缩、删除和邮件通知日志。配置文件通常位于/etc/logrotate.d/*和/etc/logrotate.conf,通过配置参数如daily、rotate、notifempty等来定制日志滚动规则。在Linux系统中,cron任务每天执行logrotate,确保日志不会撑爆磁盘。logrotate的使用和配置对于系统的稳定运行至关重要。
最近由于最近上一个了项目,但是项目的本身没有做日志的滚动,导致日志一直在增长,这样下去肯定会撑爆磁盘,导致不可预测的结果   
这个适合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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值