nginx日志文件自动切分以及过期文件删除

本文使用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 B

Handling 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博客

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值