【运维工具】logrotate 日志管理神器

服务器经常会产生各种各样的日志文件,我们需要定期清理


日志的分类

  • 系统日志

  • 应用日志


系统日志

例如系统的history 历史信息   crontab的运行日志  一般系统日志系统都帮我们运维好了,不需要额外配置

应用日志

例如nginx  的access 和 error 日志 ,php框架的运行日志,这些日志是我们排查问题的有力证据

工具logrotate

logrotate是什么

logrotate是大多数linux系统自带的日志切割工具

logrotate的适用场景

logrotate常用来切割仍在被写的“动态”文件,它支持 按时间间隔或文件大小 来触发文件的自动切分(automatic rotation)


实战

按天保存一周的Nginx日志压缩文件,保留30天,配置文件为「/etc/logrotate.d/nginx」

最后代码如下(本人ubuntu系统)

/data/logs/nginx/*.log {
        daily
	dateext
        missingok
	dateformat %Y%m%d
        extension .log
        rotate 30
        compress
        delaycompress
        notifempty
        create 640 nginx adm
        sharedscripts
        postrotate
                [ -f /var/run/nginx.pid ] && kill -USR1 `cat /var/run/nginx.pid`
        endscript
}


手动执行(-d debug模式 )

$ logrotate -d -f /etc/logrotate.d/nginx



具体logrotate更多用法请自行学习