1. 程式人生 > 實用技巧 >Nginx 日誌切分

Nginx 日誌切分

logrotate

vim /etc/logrotate.d/nginx

/usr/local/nginx/logs/*.log {
    daily              # 指定轉儲週期為每天
    rotate 7           # 保留7份
    missingok          # 如果日誌丟失,不報錯繼續滾動下一個日誌
    notifempty         # 當日志文件為空時,不進行輪轉
    dateext            # 使用當期日期作為命名格式
    sharedscripts      # 執行postrotate指令碼,作用是在所有日誌都輪轉後統一執行一次指令碼。如果沒有配置這個,那麼每個日誌輪轉後都會執行一次指令碼
    postrotate           # 在logrotate轉儲之後需要執行的指令,例如重新啟動 (kill -HUP) 某個服務!必須獨立成行
        if [ -f /usr/local/nginx/logs/nginx.pid ]; then
            kill -USR1 `cat /usr/local/nginx/logs/nginx.pid` # ## 向 Nginx 主程序傳送 USR1 訊號。USR1 訊號是重新開啟日誌檔案
        fi
    endscript
}

Nginx

log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                  '$status $body_bytes_sent "$http_referer" '
                  '"$http_user_agent" "$http_x_forwarded_for"';

map $time_iso8601 $logdate {
  '~^(?<ymd>\d{4}-\d{2}-\d{2})' $ymd;
  default                       'date-not-found';
}

access_log logs/access-$logdate.log main;
open_log_file_cache max=10;

shell指令碼

#!/bin/bash

yesterday=`date -d "-1 days" +'%Y%m%d'`
cd `dirname $0`
basedir=`pwd`
logdir="${basedir}/bak"
bindir="${basedir%/*}/sbin"
mkdir -p ${logdir}

for log in `ls *.log 2>/dev/null`
do
    mv ${log} ${logdir}/${log}.${yesterday}.bak
    # gzip ${logdir}/${log}.${yesterday}
done

${bindir}/nginx -s reload

cd ${logdir}
find . -type f -name "*.bak" -mtime +7 | xargs rm -f

日誌壓縮

#!/usr/bin/sh
#根據系統/服務/日誌保留天數三個引數壓縮日誌
#usage: sh clearlog.sh sysname appname keepdays
sysName=$1
appName=$2
keepDay=$3
logDir=/var/log/${sysName}/${appName}
logFile=${appName}.*[0-9][0-9].log
cd ${logDir}
find ./ -name "${logFile}" -mtime -${keepDay} -exec gzip {} \;