日志的轮转是一种日志管理策略,可以简化管理。
以/var/log/messages 日志档案为例:
先分四步讲解下轮转的过程。
1. 系统只有 messages 档案,还没有轮转
touch messages
2. 第一次轮转生成 messages.1
mv messages messages.1
touch messages
3. 第二次轮转生成 messages.2
mv messages.1 messages.2
mv messages messages.1
touch messages
4. 第三次轮转生成 messages.3
mv messages.2 messages.3
mv messages.1 messages.2
mv messages messages.1
toouch messages
这样日志达到一定条件就会这样不断生成新的档案,可以看出,日志的轮转其本质就是旧档案的移动和新档案的建立。
———————————————————————-
日志的轮转其主配置档案为/etc/logrotate.conf
[root@localhost ~]# cat /etc/logrotate.conf|grep -v ^# |grep -v ^$
weekly
rotate 4
create
include /etc/logrotate.d
/var/log/wtmp {
monthly
minsize 1M
create 0664 root utmp
rotate 1
}
全域性配置:
weekly :表示所有日志每周进行一次轮转
rotate 4 :表示所有日志预设只保留一个旧档案
create :由于旧档案被轮转了,所以新建一个日志档案来储存日志
include /etc/logrotate.d :次配置档案所在目录
 
/var/log/wtmp 为区域性配置:
monthly :表示所有日志每周进行一次轮转
minsize 1M :轮转日志的最小大小
create 0664 root utmp :建立档案时,指定许可权、属主和属组
rotate 1 :保留一个旧档案
这全域性配置和区域性配置就类似 C++中类的继承。
———————————————————————-
自定义日志轮转:
自定义日志轮转前要了解下面几个命令:
需要执行的外部命令放在 sharedscripts 和 endscript 两行之间
prerotate : logrotate 命令执行前执行指令码内容
postrotate:logrotate 命令执行后执行指令码内容
———————————————————————-
下面说个例项:
配置/var/log/mytest.log 日志档案记录所有日志,并加上高阶许可权 a;
echo “*.info/var/log/mytest.log”>>/etc/syslog.conf
/etc/init.d/syslog restart
chattr +a /var/log/mytest.log
轮转配置
vim /etc/logrotate.d/mytest
/var/log/mytest.log{
mothly
size=10M
rotate 5
compress 压缩储存
sharedscripts
prerotate
/usr/bin/chattr -a /var/log/mytest.log
endscripts
sharedscripts
postrotate
/usr/bin/kill -HUP syslog  以 HUP 方式从新载入服务,相当于从新读取配置档案,不改变程序 id 号
/usr/bin/chattr +a /var/log/mytest.log
endscripts
}
最后可以用下这个命令:
# logrotate -v /etc/logrotate.conf
测试有没有日志需要轮转-f 强制轮转