Q:在/var/log/nginx/目录发现以 access.log.[数字].gz 与 error.log.[数字].gz 格式命名的文件,每天一个。
A:默认nginx不会自动切割日志,可以使用Linux的logrotate可以自动对日志进行切割,压缩和删除。而且自动化处理,不需要人为操作,使用非常方便。
全局配置文件:/etc/logrotate.conf
logrotate并不是一个常驻进程,而是通过cron计划任务定期执行。默认情况下,它每天会被执行一次,由/etc/cron.daily/logrotate脚本调用。logrotate会读取配置文件(通常是 /etc/logrotate.conf 和 /etc/logrotate.d/ 目录下的文件),根据配置规则来处理日志文件。
grep -Ev '^#|^$' /etc/logrotate.conf
weekly
su root adm
rotate 4
create
include /etc/logrotate.d
手动运行:
- 参数
-d代表测试,不会真实循任何日志文件。 - 参数
-f可以立即触发一次轮转,无视正常的时间表。
sudo logrotate /etc/logrotate.conf # 调用/etc/lograte.d/下的所有配置并执行
sudo logrotate /etc/logrotate.d/xxx_file # 为某个特定的配置调用执行
sudo cat /var/lib/logrotate/status # 查看状态文件来确认执行记录
应用配置文件:/etc/logrotate.d/nginx
如果不需要轮转日志文件,就删除配置文件。
/var/log/nginx/*.log {
daily
missingok
rotate 52
compress
delaycompress
notifempty
create 640 nginx adm
sharedscripts
postrotate
if [ -f /run/nginx.pid ]; then
kill -USR1 `cat /run/nginx.pid`
fi
endscript
}
指令解释
daily指定转储周期为每天,还有周weekly、月monthlymissingok如果日志丢失,不报错继续滚动下一个日志rotate 52指定日志文件删除之前转储的次数,0 指没有备份,52 指保留52 个备份compress通过gzip 压缩转储以后的日志,nocompress指不做gzip压缩处理delaycompress和compress一起使用时,转储的日志文件到下一次转储时才压缩;nodelaycompress指转储同时压缩notifempty当日志文件为空时,不进行轮转;ifempty即使日志文件为空文件也做轮转create 640 nginx adm轮转时指定创建新文件的属性sharedscripts运行postrotate脚本,作用是在所有日志都轮转后统一执行一次脚本。如果没有配置这个,那么每个日志轮转后都会执行一次脚本postrotate在logrotate转储之后需要执行的指令,例如重新启动 (kill -HUP) 某个服务!必须独立成行;prerotate指在logrotate转储之前需要执行的指令,例如修改文件的属性等动作;必须独立成行kill -USR1 'cat /var/run/nginx.pid'是一个用于 重载 Nginx 日志文件 的命令。它通过向 Nginx 主进程发送 USR1 信号,触发日志文件的重新打开操作,常用于日志轮转。- 手动运行脚本分割日志
sudo /usr/sbin/logrotate -f /etc/logrotate.d/nginx
其他指令
mail address把转储的日志文件发送到指定的E-mail 地址olddir directory转储后的日志文件放入指定的目录,必须和当前日志文件在同一个文件系统noolddir转储后的日志文件和当前日志文件放在同一个目录下dateext在切割后的日志文件名中添加日期后缀,默认格式为-%Y%m%d,例如example.log-20231015dateformat -%Y-%m-%d配合dateext使用,紧跟在下一行出现,定义文件切割后的文件名,只支持 %Y %m %d %s 这四个参数size(minsize) log-size# 当日志文件到达指定的大小时才转储,log-size能指定bytes(缺省)及KB (sizek)或MB(sizem),例如 size 100M
调整为每月轮转不压缩
/var/log/nginx/*.log {
monthly
missingok
rotate 999
nocompress
notifempty
create 640 nginx adm
dateext
dateformat .%Y%m
sharedscripts
postrotate
if [ -f /run/nginx.pid ]; then
kill -USR1 `cat /run/nginx.pid`
fi
endscript
}
验证:sudo logrotate -d /etc/logrotate.d/nginx
为什么要使用logrotate?
在ningx中配置日志文件名,使用变量名时,会出现创建了这些日志文件:nginx__.log、nginx__blog.t725.cn.log
Nginx
# access_log 按月+域名生成文件,不建议使用。在实践中,会出现日期变量没有值,甚至$host的值为空,导致有创建了这些日志文件:nginx__.log、nginx__blog.t725.cn.log
if ($time_iso8601 ~ "^\d{2}(\d{2})-(\d{2})") {
set $YY $1;
set $MM $2;
}
access_log /data/www/log/nginx_${YY}${MM}_${host}.log main;
发表回复