要自定义 Nginx 日志输出,您需要编辑 Nginx 配置文件(通常位于 /etc/nginx/nginx.conf 或 /etc/nginx/sites-available/ 目录下的某个文件)。以下是一些步骤和示例,帮助您自定义 Nginx 日志输出。
sudo nano /etc/nginx/nginx.conf 或者,如果您知道特定站点的配置文件,可以编辑该文件:
sudo nano /etc/nginx/sites-available/your-site.conf 在 http、server 或 location 块中,找到 access_log 和 error_log 指令。如果没有找到这些指令,请将它们添加到适当的块中。
自定义日志格式。在 http、server 或 location 块中,使用 log_format 指令定义一个新的日志格式。例如,以下是一个名为 custom_format 的自定义日志格式:
log_format custom_format '$remote_addr - $remote_user [$time_local] ' '"$request" $status $body_bytes_sent ' '"$http_referer" "$http_user_agent" ' '"$http_x_forwarded_for" "$request_time"'; 这个自定义格式包括远程地址、远程用户、本地时间、请求、状态码、发送的字节数、引用页、用户代理、转发请求的 IP 地址和请求时间。
access_log 指令。在 server 或 location 块中,将 access_log 指令的值更改为您刚刚创建的自定义格式。例如:access_log /var/log/nginx/access.log custom_format; 这将使 Nginx 使用 custom_format 格式记录访问日志。
error_log 指令和 log_format 指令创建一个新的错误日志格式。例如:error_log /var/log/nginx/error.log custom_error_format debug; 将 custom_error_format 替换为您选择的错误日志格式名称。
保存更改并退出编辑器。
检查 Nginx 配置文件的语法是否正确:
sudo nginx -t 如果配置文件语法正确,您将看到以下输出:
nginx: configuration file /etc/nginx/nginx.conf test is successful sudo systemctl reload nginx 现在,Nginx 将使用您自定义的日志格式输出访问和错误日志。请注意,更改日志格式可能会影响日志文件的可读性,因此请确保您选择的字段对您的需求有帮助。