温馨提示×

debian nginx慢日志怎么开

小樊
38
2026-09-04 11:09:32
栏目: 智能运维

在 Debian 上给 Nginx 开启慢日志(慢请求日志),核心是用 Nginx 的 log_format + $request_time / $upstream_response_time 配合 access_log 的 if 条件,把响应时间超过阈值的请求单独写到一个文件里(Nginx 本身没有像 MySQL 那样的 slow log 指令)。

下面给你一套最常用、可直接用的配置。


一、修改 Nginx 配置(推荐方式)

1. 编辑站点或 http 配置

一般在:

/etc/nginx/nginx.conf
或
/etc/nginx/conf.d/xxx.conf
或
/etc/nginx/sites-enabled/xxx

2. 定义慢日志格式

在 http {} 里加:

log_format slow_log '$remote_addr - $remote_user [$time_local] '
                    '"$request" $status '
                    'rt=$request_time ut=$upstream_response_time '
                    'u=$upstream_addr';

3. 在 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 秒才记慢日志

二、只看后端慢(PHP / Java / 代理)

如果你只关心后端慢:

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

五、进阶(可选)

1. 按 location 单独记录

location /api/ {
    access_log /var/log/nginx/api_slow.log slow_log if=$request_time_too_long;
}

2. 用 awk 快速统计

awk '$NF>2' /var/log/nginx/access.log

六、总结

✅ Debian 上 Nginx 慢日志本质是:

access_log + if 条件 + request_time

如果你告诉我:

  • 是 PHP / Java / 静态文件
  • 想记 多少秒以上
  • 是否用 Docker

我可以帮你写一套精确配置。

0 踩