Linux系统日志管理工具logrotate的配置

发表时间:2017-01-20 16:50 | 分类:Linux | 浏览:1,836 次

最近在看日志管理的资料,发现网上很多朋友做日志分割很多情况是用脚本+cron实现(自己以前也是这样做的),但恰恰忘记logrotate这个好用的工具。它可以自动对日志进行截断(或轮循)、压缩以及删除旧的日志文件。Linux系统/var/log目录下的系统日志就是通过它实现的。

准备

一般主流的CentOS、Debian和Ubuntu系统都自带有安装。确认是否有该命令,执行logrotate。下面以Ubuntu系统和分割Apache日志为例,详细介绍logrotate的配置。

zhangnq@ubuntu:~$ logrotate 
logrotate 3.7.8 - Copyright (C) 1995-2001 Red Hat, Inc.
This may be freely redistributed under the terms of the GNU Public License

用法: logrotate [-dfv?] [-d|--debug] [-f|--force] [-m|--mail=command] [-s|--state=statefile] [-v|--verbose] [-?|--help] [--usage] [OPTION...] 

说明已经安装,如果提示命令不存在,就执行手动安装。

apt-get install logrotate

简单了解

logrotate是通过cron来执行,触发脚本放置在/etc/cron.daily/logrotate,内容类似如下。运行时logrotate会调用/etc/logrotate.conf主配置文件,每个应用配置放置在/etc/logrotate.d目录。

#!/bin/sh

# Clean non existent log file entries from status file
cd /var/lib/logrotate
test -e status || touch status
head -1 status > status.clean
sed 's/"//g' status | while read logfile date
do
    [ -e "$logfile" ] && echo "\"$logfile\" $date"
done >> status.clean
mv status.clean status

test -x /usr/sbin/logrotate || exit 0
/usr/sbin/logrotate /etc/logrotate.conf

配置

Logrotate简单介绍完,下面开始实际配置。我的Apache安装后默认日志放在/var/log/apache2,下面是我写的apache配置文件。

root@ubuntu:~# cat /etc/logrotate.d/apache2
/var/log/apache2/* {
        daily
        rotate 30
        compress
        delaycompress
        missingok
        notifempty
        create 644 www www
        sharedscripts
        postrotate
                /etc/init.d/apache2 restart >/dev/null
        endscript
}

说明:

1、监控/var/log/apache2目录下的所有文件,*标识通配符,也可以指定某个日志文件。
2、daily:日志文件将按天轮循。其它可用值为‘daily’,‘weekly’或者‘yearly’。
3、rotate 30:一次将存储30个归档日志,超过后时间最久的归档将被删除。
4、compress:在轮循任务完成后,已轮循的归档将使用gzip进行压缩。
5、delaycompress:总是与compress选项一起用,delaycompress选项指示logrotate不要将最近的归档压缩,压缩将在下一次轮循周期进行。这在你或任何软件仍然需要读取最新归档时很有用。
6、missingok:在日志轮循期间,任何错误将被忽略,例如“文件无法找到”之类的错误。
7、notifempty:如果日志文件为空,轮循不会进行。
8、create 644 www www:以指定的权限创建全新的日志文件,同时logrotate也会重命名原始日志文件。
9、sharedscripts:在所有的日志文件都轮转完毕后统一执行一次脚本。如果没有配置这条指令,那么每个日志文件轮转完毕后都会执行一次脚本。
10、postrotate/endscript:在所有其它指令完成后,postrotate和endscript里面指定的命令将被执行。示例中重新加载apache。

当然也可以配置size,例如“size 100M”。同时配置轮询周期和文件大小时,文件大小的优先级大。

测试

logrotate提供一个-d选项,仅做运行测试,不错实际操作。如果不想等到cron执行,也可以强制执行,把-d选项就好。

例如:

logrotate -d -f /etc/logrotate.d/apache2
logrotate -f /etc/logrotate.d/apache2

 

有关logrotate的详细配置可以参考:http://linuxcommand.org/man_pages/logrotate8.html

本文标签:

本文链接:https://www.sijitao.net/2541.html

欢迎您在本博客中留下评论,如需转载原创文章请注明出处,谢谢!

一键脚本 博客历程 留言联系 文章归档 网站地图 谷歌地图
Copyright © 2010-2024 章郎虫博客 All Rights Reserved.