linux的日志轮转

本文深入探讨了日志轮转(logrotate)的工作原理及其配置方法,解释了如何通过日志轮转解决日志文件膨胀问题,包括日志文件的定期备份、压缩、重命名以及与rsyslog的配合使用。

众所周知日志是记录用户的操作和做的改变,随着时间的增加日志文件会变得越来越大,那么就会占据本地的空间,影像系统。

日志轮转系统就是解决这个问题的方案之一,简单来说就是将日志定期作备份重新存储为一个文件,达到一定时间跨度后旧的文件就会被覆盖掉。以此来解决的日志文件过大的问题。

就是logrotate 这个东西。

rsyslog负责写日志,记录日志;logrotate负责备份,删除日志。

查看下这个软件都装了什么文件

[root@gsc666 ~]# rpm -ql logrotate 
/etc/cron.daily/logrotate
/etc/logrotate.conf
/etc/logrotate.d
/etc/rwtab.d/logrotate
/usr/sbin/logrotate
/usr/share/doc/logrotate-3.8.6
/usr/share/doc/logrotate-3.8.6/CHANGES
/usr/share/doc/logrotate-3.8.6/COPYING
/usr/share/man/man5/logrotate.conf.5.gz
/usr/share/man/man8/logrotate.8.gz
/var/lib/logrotate
/var/lib/logrotate/logrotate.status

很明显,第一个在cron.daily 目录下,是计划任务的,每天执行一次。daily嘛。

[root@gsc666 ~]# 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

很明显是一个脚本,并且是查看状态在发送一个日志。

/etc/logrotate.conf

日志轮转的主配置文件,主要是写了一些命令,默认全局生效的。

有这样一条# RPM packages drop log rotation information into this directory
include /etc/logrotate.d

表示在/logrotate.d这个目录下都生效。

意思是将日志按照功能分开,以防一个日志文件过长,给读取造成困难。类似子配置文件,标记一个目录指向和存放这些文件,其实本质上和直接写在主配置文件中一样。

# see "man logrotate" for details
# rotate log files weekly
weekly    //每周轮转

# keep 4 weeks worth of backlogs
rotate 4    //保存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
}

# system-specific logs may be also be configured here.

可以自己创建一个日志文件,来做演示。

创建一个启动的日志。
[root@gsc666 ~]# vi /etc/rsyslog.conf 
[root@gsc666 ~]# systemctl restart rsyslog
[root@gsc666 ~]# logger -is -p local1.info "test log 2"
root[13562]: test log 2
[root@gsc666 ~]# cat /var/log/local1.log 
Oct 25 19:05:49 gsc666 root[13562]: test log 2

# Save boot messages also to boot.log
local7.*                                                /var/log/boot.log
local1.*   /var/log/local1.log
//最后的local1 就是这次添加的,配置文件是rsyslog.conf 

到这里日志的记录就达成了,现在进行的是日志的轮转。

[root@gsc666 ~]# chattr +a /var/log/local1.log 
先加个文件属性权限吧,为了后续的一个东西。

配置轮转的配置文件,就用单个文件的规则吧。

[root@gsc666 ~]# vi /etc/logrotate.d/local1
配置文件这样写:
/var/log/local1.log {  //指定一个要操作的日志文件
        prerotate   //轮转前要做的事
           chattr -a /var/log/local1.log    //去掉文件属性权限  
        endscript

        missingok   //丢失不提醒
        rotate 3    //保存3份
        daily       //每日轮转
        create 0600 root root   //创建轮转日志文件的权限和属组属主

        postrotate   //轮转后要做的事
           chattr +a /var/log/local1.log
           /bin/kill -HUP `cat /var/run/syslogd.pid 2> /dev/null` 2> /dev/null || true   //初始化轮转的服务,重新读配置文件等。重要!!!
          mv /var/log/local1.log.1 /var/log/"local1.log.`date "+%s"`"  // 给生成的文件重命名,打上时间戳
        endscript
}

prerotate ,之前那个就是为了这个,在轮转前可以做一些操作。

开始测试:

[root@gsc666 ~]# logger -is -p local1.info "test log 6"  //手动发个日志
root[13897]: test log 6
[root@gsc666 ~]# logrotate -f /etc/logrotate.d/local1    //强制轮转 后边指定的是“子”的配置文件
[root@gsc666 ~]# ls /var/log/local1*   //查看日志的文件,发现有2个,一个是新生成的,一个是旧的已经轮转下来了,并且名字改变了
/var/log/local1.log  /var/log/local1.log.1572003075
[root@gsc666 ~]# cat /var/log/local1.log.1572003075 
Oct 25 19:05:49 gsc666 root[13562]: test log 2
Oct 25 19:22:36 gsc666 root[13784]: test log 3
Oct 25 19:27:17 gsc666 root[13845]: test log 4
Oct 25 19:29:05 gsc666 root[13861]: test log 5
Oct 25 19:31:02 gsc666 root[13897]: test log 6
[root@gsc666 ~]# 
//并且在这里可以看到之前的日志内容,证明这个是之前存日志的文件。

日志轮转由计划任务控制,但是具体在什么时候执行,由下边的文件控制。

[root@localhost ~ ]# vim /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

和这个文件


[root@localhost ~ ]# 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

至于为什么要初始化呢????

因为日志轮转前,日志记录到一个文件中,识别这个文件的inode,这时进行轮转生成了一个新的文件,但是日志还是记录到旧的文件中,这是不对的,就需要重新读一下,让系统知道,新的文件的名字,和inode。这样才能备份旧的文件,并且日志记录到新的文件中。

PS:驱动主配置文件也可以强制轮转,生成的文件后也有时间戳不过和我的规则不同,没有log.1这个文件所以报错,不过不影响,轮转文件也生成了。

[root@gsc666 ~]# logrotate -f /etc/logrotate.conf 
mv: cannot stat ‘/var/log/local1.log.1’: No such file or directory
error: error running non-shared postrotate script for /var/log/local1.log of '/var/log/local1.log '
[root@gsc666 ~]# ls /var/log/local1*
/var/log/local1.log  /var/log/local1.log.1572003075  /var/log/local1.log-20191025

PS : logdotate 的属性

compress 					通过gzip 压缩转储以后的日志
nocompress 					不做gzip压缩处理
create mode owner group 	轮转时指定创建新文件的属性,如create 0777 nobody nobody
nocreate 					不建立新的日志文件
delaycompress 和compress 	一起使用时,转储的日志文件到下一次转储时才压缩
nodelaycompress 			覆盖 delaycompress 选项,转储同时压缩。
missingok 					如果日志丢失,不报错继续滚动下一个日志
ifempty 					即使日志文件为空文件也做轮转,这个是logrotate的缺省选项。
notifempty 					当日志文件为空时,不进行轮转
mail address 				把转储的日志文件发送到指定的E-mail 地址
olddir directory 			转储后的日志文件放入指定的目录,必须和当前日志文件在同一个文件系统
noolddir 					转储后的日志文件和当前日志文件放在同一个目录下
sharedscripts 				运行postrotate脚本,作用是在所有日志都轮转后统一执行一次脚本。如果没有配置这个,那么每个日志轮转后都会执行一次脚本
prerotate 					在logrotate转储之前需要执行的指令,例如修改文件的属性等动作;必须独立成行
postrotate 					在logrotate转储之后需要执行的指令,例如重新启动 (kill -HUP) 某个服务!必须独立成行
daily 						指定转储周期为每天
weekly 						指定转储周期为每周
monthly 					指定转储周期为每月
rotate count 				指定日志文件删除之前转储的次数,0 指没有备份,5 指保留5 个备份
dateext 					使用当期日期作为命名格式
dateformat .%s 				配合dateext使用,紧跟在下一行出现,定义文件切割后的文件名,必须配合dateext使用,只支持 %Y %m %d %s 这四个参数
size(或minsize) log-size 	当日志文件到达指定的大小时才转储,log-size能指定bytes(缺省)及KB (sizek)或MB(sizem).

	当日志文件 >= log-size 的时候就转储。 以下为合法格式:(其他格式的单位大小写没有试过)
	size = 5 或 size 5 (>= 5 个字节就转储)
	size = 100k 或 size 100k
	size = 100M 或 size 100M

如果设置了size,会无视 daily, weekly,monthly 指令,所以size的优先级比较高 
<think>我们正在讨论Linux日志轮转中的maxage参数。maxage是logrotate配置文件中的一个选项,用于指定日志文件在轮转后保留的最大天数。超过这个天数的旧日志文件将被删除。 引用说明:参考了logrotate的man手册和常见配置实践。 配置示例: /var/log/syslog { rotate 7 daily maxage 7 compress delaycompress missingok notifempty create 644 root root } 在这个例子中,maxage 7表示轮转后的日志文件最多保留7天。也就是说,7天之前的日志文件会被删除。 注意:maxage和rotate的区别: - rotate:指定保留的轮转文件数量。例如,rotate 7会保留最近的7个轮转文件(如syslog.1.gz, syslog.2.gz, ... syslog.7.gz)。 - maxage:指定按天数删除旧日志。即使轮转文件的数量没有达到rotate指定的数量,只要文件超过maxage指定的天数,也会被删除。 因此,maxage可以确保即使日志轮转没有按预期发生(比如因为服务器停机),旧日志也不会无限期保留。 使用maxage时,通常与daily、weekly、monthly等时间间隔选项一起使用,也可以配合size选项使用(当日志达到一定大小时轮转)。 注意事项: 1. maxage删除的是轮转后的日志文件(即已经经过压缩或重命名的文件),而不是当前的活动日志文件。 2. 删除操作在每次轮转时执行。 所以,用户可以根据需要设置maxage来管理日志的保留时间,避免磁盘空间被旧日志占满。 相关问题: 1. logrotate中的rotate和maxage参数有什么区别? 2. 如何配置logrotate以同时按时间和大小轮转日志? 3. 除了maxage,还有哪些参数可以控制日志保留?</think>### Linux日志轮转中的maxage参数详解 在Linux日志轮转配置中,`maxage`参数用于**控制日志文件保留的最大天数**。其核心作用是自动删除超过指定天数的旧日志文件,防止日志文件无限增长占用磁盘空间。 #### 参数作用 1. **时间驱动清理**:根据文件修改时间(mtime)而非轮转次数清理日志 2. **安全保障**:当日志轮转因故障中断时,仍能按时间阈值清理旧日志 3. **精确控制**:与`rotate`参数互补(`rotate`控制保留文件数量,`maxage`控制保留时长) #### 配置语法 在`/etc/logrotate.d/`目录的配置文件中: ```conf /path/to/logfile { daily maxage 30 # 保留最近30天的日志 rotate 7 # 同时保留7个轮转文件 compress missingok } ``` #### 典型使用场景 1. **合规性要求**:法规要求日志保留30天 ```conf /var/log/secure { weekly maxage 30 # 满足合规保留期 } ``` 2. **磁盘空间有限**:在嵌入式系统中限制日志存储时长 ```conf /var/log/app.log { size 10M maxage 7 # 超过7天自动删除 } ``` 3. **高流量服务**:配合`rotate`防止日志爆炸性增长 ```conf /var/log/nginx/*.log { daily rotate 365 maxage 60 # 双重保障:最多保留60天 } ``` #### 注意事项 1. **时间计算基准**:基于日志文件的`修改时间`(可通过`stat`命令验证) 2. **删除时机**:仅在日志轮转执行时检查并删除超期文件 3. **与rotate关系**: - 当`maxage`和`rotate`同时存在时,**先执行数量删除**(`rotate`),**再执行时间删除**(`maxage`) - 例如`rotate 7 + maxage 30`:先保留7个文件,再从这7个中删除30天前的 #### 最佳实践 ```conf # 完整示例:Apache日志配置 /var/log/apache2/*.log { daily missingok rotate 14 maxage 60 # 最终保留不超过60天 compress delaycompress notifempty create 640 root adm sharedscripts postrotate /usr/sbin/apachectl graceful endscript } ``` > 此配置实现双重清理机制:首先保留14个轮转文件,再删除其中超过60天的文件[^1]。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值