编程技术分享平台

网站首页 > 技术教程 正文

logrotate轮转nginx日志(nginx轮询)

xnh888 2024-09-21 06:18:12 技术教程 40 ℃ 0 评论

编辑 /etc/logrotate.d/nginx

/var/log/nginx/*.log {
        daily # 每日轮转
        missingok
        rotate 14 # 保留14天的数据
        dateext # 支持日期格式名称的切割方式
        dateformat -%Y%m%d  # 定义文件名称
        delaycompress
        notifempty
        create 0640 www-data adm
        sharedscripts
        prerotate
                if [ -d /etc/logrotate.d/httpd-prerotate ]; then \
                        run-parts /etc/logrotate.d/httpd-prerotate; \
                fi \
        endscript
        postrotate
                # 告诉 nginx 重新打开日志文件,以便实现日志切割,默认的语句不生效
                nginx -s reopen >/dev/null 2>&1

              	# 自定义日志文件备份
                cur_date=$(date +%Y%m%d)
                if [ ! -d /data/backup/nginx ];then
                        mkdir -p /data/backup/nginx
                fi
                cp -f /var/log/nginx/*-$cur_date /data/backup/nginx
        endscript
}

为什么要编辑这个文件?

  1. 按需定义功能,如定义文件的名称、保留的天数、轮转的时机,是否压缩以及备份等功能
  2. 原来的轮转脚本运行后,日志不会写入access.log

手动触发日志轮转

sudo logrotate -f /etc/logrotate.conf

任务轮转的时机

触发机制定义在这里 /etc/crontab

# Example of job definition:
# .---------------- minute (0 - 59)
# |  .------------- hour (0 - 23)
# |  |  .---------- day of month (1 - 31)
# |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ...
# |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# |  |  |  |  |
# *  *  *  *  * user-name command to be executed
17 *    * * *   root    cd / && run-parts --report /etc/cron.hourly
25 6    * * *   root    test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.daily )
47 6    * * 7   root    test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.weekly )
52 6    1 * *   root    test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.monthly )
  • 第一行 (17 * * * * root cd / && run-parts --report /etc/cron.hourly) 表示每小时的第 17 分钟执行 /etc/cron.hourly 目录中的所有脚本。
  • 第二行 (25 6 * * * root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.daily )) 表示每天的第 6 小时 25 分钟执行 /etc/cron.daily 目录中的所有脚本。
  • 第三行 (47 6 * * 7 root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.weekly )) 表示每周的第 7 天(星期天)的第 6 小时 47 分钟执行 /etc/cron.weekly 目录中的所有脚本。
  • 第四行 (52 6 1 * * root test -x /usr/sbin/anacron || ( cd / && run-parts --report /etc/cron.monthly )) 表示每月的第 1 天的第 6 小时 52 分钟执行 /etc/cron.monthly 目录中的所有脚本。

这些行的各个字段解释如下:

  1. 第一个字段:分钟 (0 - 59)
  2. 第二个字段:小时 (0 - 23)
  3. 第三个字段:月份中的某一天 (1 - 31)
  4. 第四个字段:月份 (1 - 12) 或者缩写的月份名称
  5. 第五个字段:星期中的某一天 (0 - 6),星期天可以是 0 或 7,或者缩写的星期名称
  6. user-name:指定了使用哪个用户执行命令
  7. command to be executed:要执行的命令

因此,你可以根据这个格式查看系统中定期运行的 cron 任务。如果你想了解更多关于 cron 任务的信息,可以查看 /etc/cron.d/ 和 /etc/crontab 等文件,以及 /etc/cron.daily/、/etc/cron.weekly/ 和 /etc/cron.monthly/ 目录。

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表