本文使用logrotate进行日志文件切分管理
一、原理
切分原始是通过向 Nginx 主进程发送 USR1信号。
USR1信号量被 Nginx 自定义了,为重新打开日志;当 kill 命令发送 USR1时,nginx 会重新打开日志文件,并重新创建进程。
nginx.pid文件存放的是master进程的id,一般保存在/var/run或者/usr/local/nginx/logs目录下
# nginx 官方提供的日志滚动方式
$ mv access.log access.log.0
$ kill -USR1 `cat master.nginx.pid`
$ sleep 1
$ gzip access.log.0 # do something with access.log.0
二、logrotate
logrotate
是一个日志文件管理工具。用于分割日志,删除旧的日志,并创建新的日志文件,起到日志滚动的作用。
logrotate
是基于 linux 的 CRON 来运行的,其脚本是 /etc/cron.daily/logrotate
1、安装logrotate
Linux一般会默认安装logrotate,配置文件默认路径为:
/etc/logrotate.conf
如果linux上没有安装,可以自行安装,通过以下命令安装
$yum install logrotate
2、配置logrotate
#nginx文件之前是不存在的,这次创建并配置任务
$vi /etc/logrotate.d/nginx
/data/log/nginx/*.log {
# 指定转储周期为每月
monthly
# 使用当期日期作为命名格式
dateext
# 如果日志丢失,不报错继续滚动下一个日志
missingok
# 保留 7 个备份
rotate 7
# 不压缩
nocompress
# 整个日志组运行一次的脚本
sharedscripts
# 转储以后需要执行的命令
postrotate
# 重新打开日志文件
[ ! -f /usr/local/nginx/logs/nginx.pid ] || kill -USR1 `cat /usr/local/nginx/logs/nginx.pid`
endscript
}
手动执行logrotate
# '-d' 调试模式(不切分日志文件),并输出详细处理过程日志
$ logrotate -d -f /etc/logrotate.d/nginx# '-f' 强制切分日志,'-v' 输出详细信息
$ logrotate -vf /etc/logrotate.d/nginx
reading config file nginx
Allocating hash table for state file, size 15360 BHandling 1 logs
rotating pattern: /usr/local/nginx/logs/*.log forced from command line (100 rotations)
empty log files are rotated, old logs are removed
considering log /usr/local/nginx/logs/access.log
log needs rotating
considering log /usr/local/nginx/logs/error.log
log needs rotating
rotating log /usr/local/nginx/logs/access.log, log->rotateCount is 100
dateext suffix '-20201121'
glob pattern '-[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]'
glob finding old rotated logs failed
rotating log /usr/local/nginx/logs/error.log, log->rotateCount is 100
dateext suffix '-20201121'
glob pattern '-[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]'
glob finding old rotated logs failed
renaming /usr/local/nginx/logs/access.log to /usr/local/nginx/logs/access.log-20201121
renaming /usr/local/nginx/logs/error.log to /usr/local/nginx/logs/error.log-20201121
running postrotate script# 切分后的日志文件
$ ls -lt /usr/local/nginx/logs
总用量 0
-rw-r--r-- 1 nginx root 0 11月 21 18:58 access.log
-rw-r--r-- 1 nginx root 0 11月 21 18:57 access.log-20201121
-rw-r--r-- 1 nginx root 0 11月 21 18:58 error.log
-rw-r--r-- 1 nginx root 0 11月 21 18:57 error.log-20201121
-rw-r--r-- 1 nginx root 0 11月 21 18:58 images.log
-rw-r--r-- 1 nginx root 0 11月 21 18:57 images.log-20201121
此文章非原创,只是记录下自己修改的部分,原创地址为:Nginx 使用 logrotate 进行日志滚动_叨叨软件测试的博客-CSDN博客