1. 背景
今天排查线上问题,由于没有查看实际日志文件大小,直接用vim打开,导致一度卡住打不开,立马反应过来,可能是日志文件太大,然后ll -ah 查看了一下日志文件131G,基于此,处理完线上问题后,马上处理nginx日志切割问题。
/usr/local/nginx/logs #nginx日志默认存放目录
/usr/local/nginx/conf #nginx配置文件
2. logrotate系统工具
主流的linux系统版本,都默认安装logrotate包,作为分割日志的系统工具,可以方便将日志按周期(日,周,月)和大小进行分割,其核心配置文件如下:
/etc/logrotate.conf #核心配置
/etc/logrotate.d/ #存储自定义配置目录
logrotate是基于crontab运行的,参见crontab的配置文件/etc/anacrontab。系统会按照计划的频率运行logrotate,通常是每天。
3. 配置说明
# see "man logrotate" for details
# rotate log files weekly,以周为周期
weekly
# keep 4 weeks worth of backlogs 保留4个文件
rotate 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.
4. nginx日志切割配置
在/etc/logrotate.d/下创建日志切割文件api-access,并定义如下处理逻辑(以周为切割周期)
/usr/local/nginx/logs/api-access.log { #轮询的日志路径
weekly #以周为周期,其他daily,monthly,weekly,yearly
rotate 7 #保留7个日志文件
notifempty #空文件不滚动切割
missingok #湖绿错误
create 644 www root: #以指定的权限创建全新的日志文件
sharedscripts #rotate之后执行命令,重新生成日志文件
postrotate #最常见的就是让应用重启
/usr/local/nginx/sbin/nginx -s reload
endscript
}
然后在/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
5.执行流程
6. 参考文档
1 https://www.nginx.com/resources/wiki/start/topics/examples/logrotation/
2 https://zhuanlan.zhihu.com/p/24880144