在 CentOS 系统中,Nginx 日志格式可以通过修改 Nginx 配置文件来实现。以下是配置 Nginx 日志格式的步骤:
使用文本编辑器打开 Nginx 的主配置文件。通常情况下,该文件位于 /etc/nginx/nginx.conf。如果找不到该文件,请检查 /etc/nginx/conf.d/ 目录下的其他配置文件。
sudo vi /etc/nginx/nginx.conf
在 http 块中,使用 log_format 指令定义自定义日志格式。例如,创建一个名为 my_custom_format 的自定义日志格式:
http {
log_format my_custom_format '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent"';
...
}
在这个例子中,我们定义了一个包含以下字段的自定义日志格式:
$remote_addr:客户端 IP 地址$remote_user:远程用户(通常为空)$time_local:本地时间$request:请求行(包括请求方法、URL 和 HTTP 协议版本)$status:HTTP 状态码$body_bytes_sent:响应体的字节数$http_referer:引用页面的 URL$http_user_agent:客户端 User-Agent 信息你可以根据需要自定义日志格式,添加或删除字段。
在 server 或 location 块中,使用 access_log 指令应用自定义日志格式。例如,将自定义日志格式应用于名为 example.com 的虚拟主机:
http {
...
server {
listen 80;
server_name example.com;
access_log /var/log/nginx/example.com.access.log my_custom_format;
...
}
}
在这个例子中,我们将自定义日志格式 my_custom_format 应用于名为 example.com 的虚拟主机的访问日志。访问日志文件将保存在 /var/log/nginx/example.com.access.log。
保存配置文件的更改,并重启 Nginx 以使更改生效:
sudo systemctl restart nginx
现在,Nginx 将使用你定义的自定义日志格式记录访问日志。