默認Nginx日志格式
http { ... #log_format main '$remote_addr - $remote_user [$time_local] "$request" ' # '$status $body_bytes_sent "$http_referer" ' # '"$http_user_agent" "$http_x_forwarded_for"'; access_log log/access.log main; ... } 默認格式main記錄樣例如下: 192.168.1.1 - - [19/Mar/2022:13:28:27 +0800] "GET / HTTP/1.1" 200 14501 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36"
Nginx日志常用參數詳解
$remote_addr:記錄訪問網站的客戶端地址 $remote_user:遠程客戶端用戶名稱 $time_local:記錄訪問時間與時區 $request:表示request請求頭的行 $status:http狀態碼,記錄請求返回的狀態,例如:200、404、301等 $body_bytes_sent:服務器發送給客戶端的響應body字節數 $http_referer:記錄此次請求是從哪個鏈接訪問過來的,可以根據refer進行防盜鏈設置 $http_user_agent:記錄客戶端訪問信息,例如:瀏覽器,手機客戶端等 $http_x_forwarded_for:當前端有代理服務器時,設置Web節點記錄客戶端地址的配置,此參數生效的前提是代理服務器上也進行了相關的http_x_forwarded_for設置 $ssl_protocol:SSL協議版本 $ssl_cipher:交換數據中的算法 $upstream_status:upstream狀態 $upstream_addr:當ngnix做負載均衡時,可以查看后台提供真實服務的設備 $upstream_response_time:請求過程中,upstream響應時間 $request_time:整個請求的總時間 $args:這個變量等於請求行中的參數,同$query_string $content_length:請求頭中的Content-length字段。 $content_type:請求頭中的Content-Type字段。 $document_root:當前請求在root指令中指定的值。 $host:請求主機頭字段,否則為服務器名稱。 $http_user_agent:客戶端agent信息 $http_cookie:客戶端cookie信息 $limit_rate:這個變量可以限制連接速率。 $request_method:客戶端請求的動作,通常為GET或POST。 $remote_addr:客戶端的IP地址。 $remote_port:客戶端的端口。 $remote_user:已經經過Auth Basic Module驗證的用戶名。 $request_filename:當前請求的文件路徑,由root或alias指令與URI請求生成。 $scheme:HTTP方法(如http,https)。 $server_protocol:請求使用的協議,通常是HTTP/1.0或HTTP/1.1。 $server_addr:服務器地址,在完成一次系統調用后可以確定這個值。 $server_name:服務器名稱。 $server_port:請求到達服務器的端口號。 $request_uri:包含請求參數的原始URI,不包含主機名,如:”/foo/bar.php?arg=baz”。 $uri:不帶請求參數的當前URI,$uri不包含主機名,如”/foo/bar.html”。 $document_uri:與$uri相同。
如何自定義日志格式
[root@service conf]# vim /usr/local/nginx/conf/nginx.conf http { ... #log_format main '$remote_addr - $remote_user [$time_local] "$request" ' # '$status $body_bytes_sent "$http_referer" ' # '"$http_user_agent" "$http_x_forwarded_for"'; # 全局定義 log_format self_access '$remote_addr - $remote_user [$time_local] "$request" ' '$status $upstream_addr $upstream_status $upstream_response_time' '$request_time $body_bytes_sent "$http_referer" ' '"$http_user_agent"'; # 定義全局access日志並引用格式 access_log /var/log/nginx/access.log self_access; ... server { listen 80; server_name www.test.com; # 定義當前server-access日志並引用格式 access_log /var/log/nginx/test.access.log self_access; location / { ... } } # include vhost/*.conf; } 輸出格式如下: 192.168.1.1 - - [19/Mar/2022:16:03:53 +0800] "GET / HTTP/1.1" 304 192.168.1.10:80 304 0.0020.002 0 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36" 192.168.1.1 - - [19/Mar/2022:16:03:53 +0800] "GET / HTTP/1.1" 200 192.168.1.20:80 200 0.0030.003 14501 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/97.0.4692.99 Safari/537.36"