使用logrotate定期切割nginx日志

前言

默认情况下,nginx的日志都会写到access.log文件中,访问流量大的话,日志文件很快就会膨胀到几十G,不方便分析处理,也占用硬盘空间。借助linux自带的logrotate工具可以很方便地实现日志自动分割。

  • nginx日志目录:/usr/local/nginx/logs/

按天切割nginx日志的配置

vim /etc/logrotate.d/nginx

/usr/local/nginx/logs/*.log {
    daily
    size 10M
    minsize 10M
    rotate 30
    missingok
    notifempty
    compress
    nodelaycompress
    copytruncate
    dateext
    dateformat -%Y-%m-%d
    dateyesterday
    postrotate
        if [ -f /usr/local/nginx/logs/nginx.pid ];then
            kill -USR1 `cat /usr/local/nginx/logs/nginx.pid`
        fi
    endscript
}

配置说明:

  • 按天切割
  • 文件大小为10M的时候才切割
  • 保留最近30天的日志文件
  • 切割中遇到日志错误忽略
  • 日志如果为空将不进行切割和压缩
  • 以gzip压缩
  • 不要将刚切割后的日志文件放到下个循环中进行压缩
  • 切割后的日志文件添加扩展名
  • 扩展名为年月日
  • 扩展名的年月日为昨天的日期
  • 在切割后执行 postrotate/endscript之间的命令,此处为热重启nginx

logrotate常用配置指令

指令 说明
daily 日志归档周期为1天。默认周期
hourly 日志归档周期为1小时
weekly 日志归档周期为1周
monthly 日志归档周期为1月,通常为每月的第一天
size 日志文件可被归档的最小值
minsize 日志文件可被归档的最小值,没到归档周期执行时间,不会执行归档操作
maxsize 日志文件大小超过设定值时,即使没到归档周期执行时间,也会执行归档操作
rotate 保留归档文件数,默认为0
missingok 如果日志文件不存在,则不显示错误信息
nomissingok 如果日志文件不存在,则显示错误信息。默认配置
notifempty 如果日志文件为空,则不进行归档操作。默认配置
ifempty 即使日志文件为空,也执行归档操作
compress 对归档文件启用压缩,默认为gzip压缩
nocompress 不压缩归档文件。默认配置
compresscmd 指定压缩归档文件的命令,默认为gzip压缩
delaycompress 在下一个归档周期再对当前归档文件进行压缩
nodelaycompress 不延迟压缩。默认配置

使用crontab定时执行logrotate

因为系统默认的logrotate规则可能会随机,所以直接删了默认规则,自行定义。

  1. rm -rf /etc/cron.daily/logrotate
  2. 使用crontab -e新建crontab规则:00 00 * * * /usr/sbin/logrotate -f /etc/logrotate.d/nginx,这样每天凌晨0点0分就会执行nginx日志切割。注意确认logrotate命令的位置。

脚本方式

有的环境也用shell脚本+crontab的方式实现了nginx日志切割

#!/bin/bash
# description: nginx日志切割脚本

set -u
LogDir="/home/admin/apps/openresty/nginx/logs" # nginx日志路径
Expires=15 # 日志保留时长, 15天

function init() {
    if [[ ! -d ${LogDir} ]]; then
        echo "${LogDir} not found"
        exit 1
    fi
}

function main() {
    cd ${LogDir}
    for logfile in $(ls *.log);do
        local logDate=$(date "+%F")
        local gzipfile="${logfile}-${logDate}.gz"
        gzip -c ${logfile} > ${gzipfile}
        cat /dev/null > ${logfile}
    done

    find ./* -type f -mtime +${Expires} -iname "*.gz" | xargs rm -f
}

init
main
posted @ 2021-06-22 14:23  花酒锄作田  阅读(313)  评论(0编辑  收藏  举报