最近整理公司服務(wù)器,對(duì)nginx復(fù)習(xí)了一遍檐盟。記錄下,備忘亥啦。
一個(gè)合理有效的訪問日志記錄,將對(duì)維護(hù)服務(wù)器,網(wǎng)站穩(wěn)定運(yùn)行,提供有力的幫助
variable 用到的變量
工欲善其事必先利其器,日志格式里各個(gè)變量都是啥玩意呀?
-
$remote_addr
:訪問的ip (重要) -
$http_x_forwarded_for
:代理攜帶的原始IP(重要,使用了CDN 服務(wù)器,反向代理莺褒,負(fù)載均衡需要) -
$request
:請(qǐng)求內(nèi)容(重要) -
$remote_user
:客戶端用戶名稱(這個(gè)一般沒啥卵用,基本沒取到過) -
$time_local
:訪問時(shí)間 -
$status
:請(qǐng)求狀態(tài) -
$body_bytes_sent
:發(fā)送給客戶端文件主體內(nèi)容大醒┣椤(重要) -
$http_referer
:從啥鏈接訪問過來的(雞肋的玩意遵岩,基本沒取到過) -
$http_user_agent
:瀏覽器(不一定是瀏覽器)的相關(guān)信息,(重要,比如干掉蜘蛛,比如干掉低端的hacker,特別是只會(huì)用工具的hacker) - 嗯,夠用了
log_format 訪問日志格式定制
知道了以上的變量,該來定制屬于自己的日志格式了.這段代碼寫在`http{}`里
log_format xxlog '$remote_addr [$time_local] "$request" $status <$body_bytes_sent> "$http_user_agent" $http_x_forwarded_for';
這里需要注意一點(diǎn),$http_x_forwarded_for不是默認(rèn)就有的,在有中轉(zhuǎn)服務(wù)器(CDN 服務(wù)器)設(shè)置的
比如我這業(yè)務(wù)需要是由A服務(wù)器反向代理到B服務(wù)器那么我在轉(zhuǎn)發(fā)時(shí),就需要帶著原始IP:`$remote_addr`
proxy_set_header X-Forwarded-For $remote_addr;
proxy_pass 192.168.1.2:8081;
access_log 設(shè)置日志文件名巡通、位置尘执、格式
一般寫在http{server{}}
里,可對(duì)不同server指定
access_log 地址 采用格式;
access_log /home/wwwlogs/web_access.log xxlog;
一些日志心得腳本
程序員最擅長干嘛?偷懶呀宴凉!偷懶靠什么,腳本呀誊锭!
- 當(dāng)天訪問數(shù)
grep "07/Dec/2016" ./web_access.log|wc -l
- 指定ip在當(dāng)天訪問情況
grep "07/Dec/2016" ./web_access.log|grep "192.168.1.2"
- 日志分割腳本
#!/bin/bash base_path='/home/wwwlogs' log_path=$(date -d yesterday +"%Y%m") day=$(date -d yesterday +"%d") mkdir -p $base_path/$log_path mv $base_path/web_access.log $base_path/$log_path/web_access_$day.log /usr/local/nginx/sbin/nginx -s reopen
-
crontab
定時(shí)任務(wù),這里為2點(diǎn)1分crontab -e 01 02 * * * /xxx/xxx/nginx_split.sh