使用logrotate工具对linux日志文件进行切割

logrotate是个好工具,运维同学可以好好研究一下。linux日志文件如果不定期清理,会填满整个磁盘。这样会很危险,因此日志管理是系统管理员日常工作之一。我们可以使用"logrotate"来管理linux日志文件,它可以实现日志的自动滚动,日志归档等功能。下面以nginx日志文件来讲解下logrotate的用法。

配置:

1、在/etc/logrotate.d目录下创建一个nginx的配置文件"nginx"配置内容如下

#vim /etc/logrotate.d/nginx
/usr/local/nginx/logs/*.log {
daily
rotate 5
missingok
notifempty
sharedscripts
postrotate
    if [ -f /usr/local/nginx/logs/nginx.pid ]; then
        kill -USR1 `cat /usr/local/nginx/logs/nginx.pid`
    fi
endscript
}

保存退出。

2、执行logrotate

#/usr/sbin/logrotate -f /etc/logrotate.d/nginx

在/usr/local/nginx/logs目录中会产生

error.log
error.log.1

说明logrotate配置成功。

3、让logrotate每天进行一次滚动,在crontab中添加一行定时脚本。

#crontab -e
59 23 * * *  /usr/sbin/logrotate -f /etc/logrotate.d/nginx

每天23点59分进行日志滚动

4、配置文件说明

  • daily:日志文件每天进行滚动
  • rotate:保留最5次滚动的日志
  • notifempty:日志文件为空不进行滚动
  • sharedscripts:运行postrotate脚本
    下面是一个脚本
postrotate
    if [ -f /usr/local/nginx/logs/nginx.pid ]; then
        kill -USR1 `cat /usr/local/nginx/logs/nginx.pid`
    fi
endscript

脚本让nginx重新生成日志文件。

配置实例

这是我的服务器上的配置,保留7天内的日志,其它的日志删除

1.nginx日志实例

more /etc/logrotate.d/nginx 
/usr/local/nginx/logs/access.log {
daily
dateext
rotate 7
missingok
notifempty
copytruncate
}

2.RabbitMQ日志实例

[root@git logrotate.d]# cat  rabbitmq-server
/var/log/rabbitmq/*.log {
        weekly
        missingok
        rotate 20
        compress
        delaycompress
        notifempty
        sharedscripts
        postrotate
            /usr/sbin/rabbitmqctl rotate_logs > /dev/null
        endscript
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容