日志使用用來(lái)進(jìn)行數(shù)據(jù)統(tǒng)計(jì)、問(wèn)題排錯(cuò)的重要手段。本文主要介紹 nginx 日志相關(guān)的配置如 access_log、log_format、log_not_found、rewrite_log、error_log 以及 Nginx 日志切割。
nginx日志相關(guān)涉及的配置有:
access_log:訪問(wèn)日志;
log_format:日志格式;
rewrite_log:重定向日志;
error_log:錯(cuò)誤日志;
nginx 具備非常靈活的日志記錄模式,每個(gè)級(jí)別的配置可以有各自獨(dú)立的訪問(wèn)日志。日志格式通過(guò) log_format 命令來(lái)定義。
語(yǔ)法:
默認(rèn)值: access_log logs/access.log combined;
使用默認(rèn) combined 格式記錄日志:access_log logs/access.log 或 access_log logs/access.log combined;
配置段: http, server, location, if in location, limit_except
參數(shù)解釋:
語(yǔ)法:log_format name string ……;
默認(rèn)值: log_format combined "……";
配置段: http
釋義:name 表示格式名稱,string 表示等義的格式。log_format 有一個(gè)默認(rèn)的無(wú)需設(shè)置的 combined 日志格式,相當(dāng)于 apache 的 combined 日志格式。
示例1:
log_format main '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent"';
示例2:
log_format proxy '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_user_agent" ';
配置相關(guān)變量釋義:
$remote_addr:表示客戶端地址;
$remote_user:表示http客戶端請(qǐng)求Nginx認(rèn)證的用戶名;
$time_local:Nginx通用日志格式下的本地時(shí)間;
$request:request請(qǐng)求行,請(qǐng)求的URL、GET等方法、HTTP協(xié)議版本;
$request_length:請(qǐng)求的長(zhǎng)度;
$request_time:請(qǐng)求處理時(shí)間,單位為秒,精度為毫秒;
$status:response返回狀態(tài)碼;
$body_bytes_sent:發(fā)送給客戶端的字節(jié)數(shù),不包括響應(yīng)頭的大小,即服務(wù)端響應(yīng)給客戶端body信息大小;
$http_referer:http上一級(jí)頁(yè)面,即從哪個(gè)頁(yè)面鏈接訪問(wèn)過(guò)來(lái)的,用于防盜鏈、用戶行為分析;
$http_user_agent:http頭部信息,記錄客戶端瀏覽器相關(guān)信息;
$connection:連接的序列號(hào);
$connection_requesta:當(dāng)前通常一個(gè)連接獲得的請(qǐng)求數(shù)量;
$msec:日志寫(xiě)入時(shí)間,單位為秒,精度為毫秒;
$pipe:如果請(qǐng)求是通過(guò)HTTP流水線(pipelined)發(fā)送,pipe值為‘p’,否則為“.”;
$http_x_forwarded_for:http請(qǐng)求攜帶的http信息。
提示:如果nginx位于負(fù)載均衡器,squid,nginx反向代理之后,web服務(wù)器無(wú)法直接獲取到客戶端真實(shí)的IP地址了。 $remote_addr獲取反向代理的IP地址。反向代理服務(wù)器在轉(zhuǎn)發(fā)請(qǐng)求的http頭信息中,可以增加X(jué)-Forwarded-For信息,用來(lái)記錄客戶端IP地址和客戶端請(qǐng)求的服務(wù)器地址。