要设置 Nginx 日志格式,您需要编辑 Nginx 配置文件。以下是一个示例,展示了如何自定义 Nginx 日志格式:
打开 Nginx 配置文件。通常位于 /etc/nginx/nginx.conf 或 /etc/nginx/sites-available/your_domain.conf。
在 http 块中,定义一个新的日志格式。例如,创建一个名为 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" "$request_time"';
# ...
}
在这个示例中,我们定义了一个名为 custom_log_format 的日志格式,其中包含了远程地址、远程用户、本地时间、请求、状态码、发送的字节数、引用页、用户代理、转发地址和请求时间等信息。
server 或 location 块中,使用新定义的日志格式。例如,将 access_log 指令设置为使用 custom_log_format:server {
# ...
access_log /var/log/nginx/your_domain.access.log custom_log_format;
# ...
}
在这个示例中,我们将 access_log 指令设置为使用 custom_log_format,并将日志文件存储在 /var/log/nginx/your_domain.access.log。
sudo nginx -t # 检查配置文件语法是否正确
sudo nginx -s reload # 重新加载配置文件
现在,Nginx 将使用您定义的自定义日志格式记录访问日志。