在 CentOS 系统中,要自定义 Nginx 日志格式,你需要编辑 Nginx 的配置文件。以下是自定义日志格式的步骤:
/etc/nginx/nginx.conf 或 /etc/nginx/conf.d/default.conf。你可以使用文本编辑器(如 vim、nano 等)打开它。例如,使用 vim 编辑器:sudo vim /etc/nginx/nginx.conf
或者
sudo vim /etc/nginx/conf.d/default.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" '
'"$http_x_forwarded_for"';
...
}
在这个例子中,我们定义了一个包含以下字段的自定义日志格式:
$remote_addr:客户端 IP 地址$remote_user:远程用户(通常为空)$time_local:本地时间$request:请求行(包括请求方法、URL 和 HTTP 协议版本)$status:响应状态码$body_bytes_sent:发送给客户端的响应体字节数$http_referer:引用页面的 URL$http_user_agent:客户端 User-Agent 信息$http_x_forwarded_for:客户端 IP 地址(如果经过代理)你可以根据需要添加或删除字段。有关可用变量的完整列表,请参阅 Nginx 文档:http://nginx.org/en/docs/http/ngx_http_core_module.html#log_format
server 或 location 块中,使用 access_log 指令指定自定义日志格式。例如,将自定义日志格式应用于名为 my_custom_log 的访问日志文件:server {
...
access_log /var/log/nginx/my_custom_log my_custom_format;
...
}
保存配置文件并退出编辑器。
重新加载 Nginx 以应用更改:
sudo nginx -t # 检查配置文件语法是否正确
sudo systemctl reload nginx # 重新加载 Nginx 配置
现在,Nginx 将使用你定义的自定义日志格式记录访问日志。