要自定义 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)或在应用程序中设置这些值。