說明:
Nginx安裝目錄:/usr/local/nginx/
Nginx日志目錄:/var/log/nginx/error/.log /var/log/nginx/access/w1/.log /var/log/nginx/access/w2/.log /var/log/nginx/access/w3/.log
nginx配置文件:nginx.conf
user www www;
.......
error_log /var/log/nginx/error/error.log error;
http {
......
log_format main 'servernameservernameremote_addr - remoteuser[remoteuser[time_local] "$request"
'statusstatusbody_bytes_sent "$http_referer" '
' "httpuseragent""httpuseragent""http_x_forwarded_for" "$request_time" ';
access_log logs/access.log main;
.......
server {
......
access_log /var/log/nginx/access/w1/access.log main;
}
include /usr/local/nginx/conf/vhost/*.conf;
}
其他站點(diǎn)只需要在server內(nèi)增加 access_log /var/log/nginx/access/w2/access.log main; 即可,
然后在相應(yīng)的日志路徑建文件夾并授權(quán)www
1、添加nginx日志切割腳本
cd /etc/logrotate.d #進(jìn)入目錄
vi /etc/logrotate.d/nginx #編輯腳本
/var/log/nginx/error/.log /var/log/nginx/access/w1/.log /var/log/nginx/access/w2/.log /var/log/nginx/access/w3/.log{
daily
rotate 15
missingok
notifempty
dateext
compress
delaycompress
create 600 www www
sharedscripts
postrotate
if [ -f /usr/local/nginx/logs/nginx.pid ]; then
kill -USR1 cat /usr/local/nginx/logs/nginx.pid
fi
endscript
}
:wq! #保存退出
chmod 644 /etc/logrotate.d/nginx #添加執(zhí)行權(quán)限
2幔嫂、執(zhí)行腳本
/usr/sbin/logrotate -vf /etc/logrotate.d/nginx
3、添加定時(shí)任務(wù)
crontab -e #添加以下代碼
0 0 * * * /usr/sbin/logrotate -vf /etc/logrotate.d/nginx #每天凌晨定時(shí)執(zhí)行腳本
至此丧慈,Linux下nginx日志每天定時(shí)切割教程完成。
備注:logrotate相關(guān)參數(shù)說明
missingok:忽略錯(cuò)誤,如“日志文件無法找到”的錯(cuò)誤提示。
dateext:切換后的日志文件會附加上一個(gè)短橫線和YYYYMMDD格式的日期灾而,沒有這個(gè)配置項(xiàng)會附加一個(gè)小數(shù)點(diǎn)加一個(gè)數(shù)字序號
notifempty:如果日志文件為空,不執(zhí)行切割扳剿。
daily:按天切割日志旁趟。可用值月:monthly 周:weekly 年:yearly
rotate 7:保留最近7天的日志記錄
sharedscripts:只為整個(gè)日志組運(yùn)行一次的腳本
postrotate和endscript:里面指定的命令將被執(zhí)行庇绽。
compress::在輪循任務(wù)完成后锡搜,已輪循的歸檔將使用gzip進(jìn)行壓縮。
delaycompress::總是與compress選項(xiàng)一起用瞧掺,delaycompress選項(xiàng)指示logrotate不要將最近的歸檔壓縮耕餐,壓縮將在下一次輪循周期進(jìn)行。這在你或任何軟件仍然需要讀取最新歸檔時(shí)很有用辟狈。
create 644 www www: 以指定的權(quán)限創(chuàng)建全新的日志文件肠缔,同時(shí)logrotate也會重命名原始日志文件夏跷。