日志配置
日志對于統計排錯來說非常有利的。本文總結了nginx日志相關的配置如access_log、log_format、open_log_file_cache、log_not_found、log_subrequest、rewrite_log、error_log。
nginx有一個非常靈活的日志記錄模式。每個級別的配置可以有各自獨立的訪問日志。日志格式通過log_format命令來定義。
ngx_http_log_module是用來定義請求日志格式的。
1. access_log指令
語法:
access_log path [format [buffer=size [flush=time]]];access_log path format gzip[=level] [buffer=size] [flush=time];access_log syslog:server=address[,parameter=value] [format];access_log off;
默認值: access_log logs/access.log combined;
配置段: http, server, location, if in location, limit_except
gzip壓縮等級。
buffer設置內存緩存區大小。
flush保存在緩存區中的最長時間。
不記錄日志:access_log off;
使用默認combined格式記錄日志:access_log logs/access.log 或 access_log logs/access.log combined;
2. log_format指令
語法: log_format name string …;
默認值: log_format combined “…”;
配置段: http
name表示格式名稱,string表示等義的格式。log_format有一個默認的無需設置的combined日志格式,相當于apache的combined日志格式,如下所示:
log_format combined '$remote_addr - $remote_user [$time_local] ' ' "$request" $status $body_bytes_sent ' ' "$http_referer" "$http_user_agent" ';
如果nginx位于負載均衡器,squid,nginx反向代理之后,web服務器無法直接獲取到客戶端真實的IP地址了。 $remote_addr獲取反向代理的IP地址。反向代理服務器在轉發請求的http頭信息中,可以增加X-Forwarded-For信息,用來記錄 客戶端IP地址和客戶端請求的服務器地址。
log_format porxy '$http_x_forwarded_for - $remote_user [$time_local] ' ' "$request" $status $body_bytes_sent ' ' "$http_referer" "$http_user_agent" ';
日志格式允許包含的變量注釋如下:
$remote_addr, $http_x_forwarded_for(反向) 記錄客戶端IP地址$remote_user 記錄客戶端用戶名稱$request 記錄請求的URL和HTTP協議$status 記錄請求狀態$body_bytes_sent 發送給客戶端的字節數,不包括響應頭的大小; 該變量與Apache模塊mod_log_config里的“%B”參數兼容。$bytes_sent 發送給客戶端的總字節數。$connection 連接的序列號。$connection_requests 當前通過一個連接獲得的請求數量。$msec 日志寫入時間。單位為秒,精度是毫秒。$pipe 如果請求是通過HTTP流水線(pipelined)發送,pipe值為“p”,否則為“.”。$http_referer 記錄從哪個頁面鏈接訪問過來的$http_user_agent 記錄客戶端瀏覽器相關信息$request_length 請求的長度(包括請求行,請求頭和請求正文)。$request_time 請求處理時間,單位為秒,精度毫秒; 從讀入客戶端的第一個字節開始,直到把最后一個字符發送給客戶端后進行日志寫入為止。$time_iso8601 ISO8601標準格式下的本地時間。$time_local 通用日志格式下的本地時間。
新聞熱點
疑難解答