在 Debian 上给 Nginx 开启慢日志(慢请求日志),核心是用 Nginx 的 log_format + $request_time / $upstream_response_time 配合 access_log 的 if 条件,把响应时间超过阈值的请求单独写到一个文件里(Nginx 本身没有像 MySQL 那样的 slow log 指令)。
下面给你一套最常用、可直接用的配置。
一般在:
/etc/nginx/nginx.conf
或
/etc/nginx/conf.d/xxx.conf
或
/etc/nginx/sites-enabled/xxx
在 http {} 里加:
log_format slow_log '$remote_addr - $remote_user [$time_local] '
'"$request" $status '
'rt=$request_time ut=$upstream_response_time '
'u=$upstream_addr';
server {} 或 location {} 里启用慢日志例如记录 超过 2 秒 的请求:
server {
listen 80;
server_name example.com;
access_log /var/log/nginx/access.log;
# 慢日志(请求时间 > 2s)
access_log /var/log/nginx/slow.log slow_log if=$request_time_too_long;
map $request_time $request_time_too_long {
default 0;
~^([2-9]|[0-9]{2,}) 1;
}
}
✅ 说明:
request_time 是 客户端总耗时upstream_response_time 是 后端处理时间map 表示:请求时间 ≥ 2 秒才记慢日志如果你只关心后端慢:
map $upstream_response_time $upstream_too_long {
default 0;
~^([1-9]|[0-9]{2,}) 1;
}
access_log /var/log/nginx/upstream_slow.log slow_log if=$upstream_too_long;
touch /var/log/nginx/slow.log
chown www-data:adm /var/log/nginx/slow.log
nginx -t
systemctl reload nginx
tail -f /var/log/nginx/slow.log
示例输出:
1.2.3.4 - - [10/Oct/2026:12:00:01 +0800] "GET /api/test HTTP/1.1" 200 rt=3.21 ut=3.10 u=127.0.0.1:9000
location /api/ {
access_log /var/log/nginx/api_slow.log slow_log if=$request_time_too_long;
}
awk '$NF>2' /var/log/nginx/access.log
✅ Debian 上 Nginx 慢日志本质是:
access_log + if 条件 + request_time
如果你告诉我:
我可以帮你写一套精确配置。