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 {} \;