要自定义 Nginx 日志格式,您需要在 Nginx 配置文件中修改 log_format 指令。以下是自定义日志格式的步骤:
打开 Nginx 配置文件。通常位于 /etc/nginx/nginx.conf 或 /etc/nginx/sites-available/your_domain.conf。
在 http 块或特定的 server/location 块中,使用 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" '
'"$http_x_forwarded_for"';
...
}
在这个例子中,我们定义了一个包含以下字段的自定义日志格式:
$remote_addr:客户端 IP 地址$remote_user:远程用户名(如果已验证)$time_local:本地时间,格式为 [day/month/year:hour:minute:second]$request:请求行,包括 HTTP 方法、请求 URI 和 HTTP 版本$status:响应状态码$body_bytes_sent:发送给客户端的响应体字节数$http_referer:引用页面的 URL(如果存在)$http_user_agent:客户端 User-Agent 信息$http_x_forwarded_for:X-Forwarded-For 请求头(如果存在)您可以根据需要添加或删除字段。有关可用变量的完整列表,请参阅 Nginx 官方文档。
server 或 location 块中,使用 access_log 指令指定要使用的日志格式。例如,将自定义日志格式应用于名为 example.com 的站点:http {
...
server {
listen 80;
server_name example.com;
access_log /var/log/nginx/example.com.access.log custom_log_format;
...
}
}
在这个例子中,我们将自定义日志格式 custom_log_format 应用于名为 example.com 的站点,并将访问日志存储在 /var/log/nginx/example.com.access.log 文件中。
sudo nginx -t # 检查配置文件语法是否正确
sudo nginx -s reload # 重新加载配置文件
现在,Nginx 将使用您定义的自定义日志格式记录访问日志。