要设置Nginx日志记录慢查询,你需要使用Nginx的access_log
指令,并结合log_format
指令自定义日志格式。以下是设置Nginx慢查询日志的步骤:
-
打开Nginx配置文件。通常位于
/etc/nginx/nginx.conf
或/etc/nginx/sites-available/your_domain.conf
。 -
在
http
块中,定义一个新的日志格式,例如命名为slow_requests
。在这个日志格式中,你可以使用$request_time
变量来记录每个请求的处理时间。例如:
http { log_format slow_requests '$remote_addr - $remote_user [$time_local] ' '"$request" $status $body_bytes_sent ' '"$http_referer" "$http_user_agent" ' '$request_time'; }
这里,$request_time
变量表示请求的处理时间,单位为秒。
- 在
server
或location
块中,使用access_log
指令指定慢查询日志文件,并引用刚刚定义的slow_requests
日志格式。例如,你可以设置一个阈值,将处理时间超过1秒的请求记录为慢查询:
server { # ... access_log /var/log/nginx/slow_queries.log slow_requests if=$slow_request; location / { # ... set $slow_request 0; if ($request_time > 1) { set $slow_request 1; } } }
这里,我们使用if
指令设置了一个变量$slow_request
,当请求处理时间超过1秒时,将其值设为1。然后,在access_log
指令中使用if=$slow_request
参数,只有当$slow_request
值为1时,才会将该请求记录到慢查询日志中。
-
保存配置文件并退出编辑器。
-
重新加载Nginx配置以应用更改:
sudo nginx -t # 检查配置文件语法是否正确 sudo nginx -s reload # 重新加载配置文件
现在,Nginx将记录处理时间超过1秒的请求到/var/log/nginx/slow_queries.log
文件中。你可以根据需要调整阈值和处理时间。