打開配置文件
通常位于 /etc/nginx/nginx.conf
或 /etc/nginx/conf.d/*.conf
,使用文本編輯器修改:
sudo nano /etc/nginx/nginx.conf
定義日志格式
在 http
塊中使用 log_format
指令自定義格式,變量用 $
開頭,常用變量包括:
$remote_addr
:客戶端IP$request
:請求行(方法+URI+協議)$status
:響應狀態碼$body_bytes_sent
:響應體字節數$request_time
:請求處理總時間(秒)$upstream_response_time
:后端響應時間(反向代理場景)http {
log_format custom '$remote_addr - $request $status $body_bytes_sent $request_time';
# 其他配置...
}
應用日志格式
在 server
或 location
塊中通過 access_log
指令引用自定義格式:
server {
access_log /var/log/nginx/access.log custom;
# 其他配置...
}
重啟Nginx生效
sudo nginx -s reload
默認格式(combined)
log_format combined '$remote_addr - $remote_user [$time_local] "$request" '
'$status $body_bytes_sent "$http_referer" '
'"$http_user_agent" "$http_x_forwarded_for"';
JSON格式
適合日志分析工具(如ELK):
log_format json '{ "time": "$time_iso8601", "ip": "$remote_addr", "request": "$request", "status": $status }';
帶緩沖的格式
提升高流量場景性能,按指定大小或時間寫入磁盤:
access_log /var/log/nginx/access.log custom buffer=32k flush=5m;
條件日志記錄
通過 map
指令過濾不需要記錄的請求(如靜態資源):
map $uri $loggable {
~^/static/ 0;
default 1;
}
access_log /var/log/nginx/access.log custom if=$loggable;
多日志文件分離
按虛擬主機或路徑拆分日志:
server {
server_name site1.example.com;
access_log /var/log/nginx/site1.access.log custom;
}
日志輪轉管理
配合 logrotate
工具避免日志占滿磁盤,示例配置:
# /etc/logrotate.d/nginx
/var/log/nginx/*.log {
daily
rotate 7
compress
missingok
create 0640 www-data adm
postrotate
/usr/sbin/nginx -s reload
endscript
}
chown -R www-data:www-data /var/log/nginx
)。buffer
)或異步寫入(如通過管道輸出到遠程服務器)。配置參考來源: