要自定義 Nginx 日志字段,您需要修改 Nginx 配置文件中的 log_format
指令。以下是自定義日志字段的步驟:
打開 Nginx 配置文件。通常位于 /etc/nginx/nginx.conf
或 /etc/nginx/sites-available/your_domain.conf
。
在 http
塊中,找到或創建一個 log_format
指令。例如,您可以創建一個名為 custom_log_format
的自定義日志格式:
http {
# ...
log_format custom_log_format '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" '
'"$custom_field1" "$custom_field2"';
# ...
}
在這個例子中,我們添加了兩個自定義字段:$custom_field1
和 $custom_field2
。您可以根據需要添加更多字段。
server
或 location
塊中,使用 access_log
指令引用您剛剛創建的自定義日志格式。例如:server {
# ...
access_log /var/log/nginx/your_domain.access.log custom_log_format;
# ...
}
這將使 Nginx 使用您定義的 custom_log_format
記錄訪問日志。
http
塊中使用 error_log
指令,并引用相同的自定義日志格式:http {
# ...
error_log /var/log/nginx/your_domain.error.log custom_log_format debug;
# ...
}
sudo nginx -t # 檢查配置文件語法是否正確
sudo nginx -s reload # 重新加載配置文件
現在,Nginx 日志將包含您定義的自定義字段。請注意,自定義字段不會自動填充任何值,因此您可能需要使用第三方模塊(如 ngx_http_realip_module 或 ngx_http_sub_module)或在應用程序中設置這些值。