Nginx 工程实践 -- 11. 日志与可观测性

日志回答"发生了什么",指标回答"现在怎么样"。前者是排障的线索,后者是发现问题的眼睛。Nginx 提供了 access_log(谁请求了什么、结果如何)、error_log(哪里出错了)和 stub_status(实时连接/请求计数)三层观测能力,再多接一个 exporter 就能接入 Prometheus 生态。

flowchart LR
    subgraph Nginx
        A["access_log
访问日志"] --> B["缓冲 / 压缩"] C["error_log
错误日志"] end B --> D["采集器
Filebeat / Promtail"] C --> D D --> E[("Loki / Elasticsearch")] E --> F["Grafana / Kibana"]

一、两类日志与记录时机

日志内容默认级别
access_log每个请求一行:来源、方法、URI、状态码、字节数、耗时等—
error_log运行错误与告警:配置错误、upstream 故障、权限问题等error

access_log 在 location 处理结束时记录;如果中途发生内部重定向,最终记在重定向后的 location 上(见第 14 篇)。

二、log_format:定义自己的字段

内置 combined 格式是常见基线,但生产上通常需要补上耗时、上游、转发信息:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
log_format main escape=json
'{"time":"$time_iso8601",'
'"remote":"$remote_addr",'
'"host":"$host",'
'"method":"$request_method",'
'"uri":"$request_uri",'
'"status":$status,'
'"bytes":$bytes_sent,'
'"req_time":$request_time,'
'"upstream_time":"$upstream_response_time",'
'"upstream":"$upstream_addr",'
'"referer":"$http_referer",'
'"ua":"$http_user_agent",'
'"request_id":"$request_id"}';

access_log /var/log/nginx/access.log main buffer=32k flush=5m;
  • escape=json:变量按 JSON 规则转义("、\、控制字符),比 default 的 \xXX 更适合直接喂给日志系统;
  • log_format 只能放在 http 块;
  • 一行太长会影响可读性,按采集端要求取舍。

三、常用变量速查

变量含义
$remote_addr / $remote_user客户端地址 / 认证用户
$time_local / $time_iso8601本地时间(CLF / ISO 8601)
$msec带毫秒的秒级时间戳
$request / $request_method / $request_uri完整请求行 / 方法 / URI(含参数)
$status响应状态码
$body_bytes_sent / $bytes_sent响应体字节 / 总发送字节(含头)
$request_time请求总耗时(从读第一个字节到发完最后一个字节)
$upstream_addr / $upstream_status上游地址 / 上游状态码
$upstream_connect_time / $upstream_header_time / $upstream_response_time与上游建连 / 收到响应头 / 收到响应 的耗时
$upstream_cache_status缓存状态(MISS/HIT/STALE 等)
$http_referer / $http_user_agentReferer / UA
$host / $server_name / $scheme / $server_port主机 / 匹配的 server_name / 协议 / 端口
$connection / $connection_requests连接序号 / 该连接上的请求数
$request_id请求唯一 ID,用于全链路串联
$http2 / $http3协商到的协议(h2 / h3)
$gzip_ratio压缩比
$arg_xxx / $cookie_xxx查询参数 / Cookie
$sent_http_xxx发给客户端的响应头

四、access_log 进阶

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# 1) 缓冲 + 定时落盘,减少小文件 IO
access_log /var/log/nginx/access.log main buffer=32k flush=5m;

# 2) 日志 gzip 压缩存储(需 zlib)
access_log /var/log/nginx/access.log main gzip flush=5m;

# 3) 按条件记录:只记非 2xx/3xx,减小量
map $status $loggable {
~^[23] 0;
default 1;
}
access_log /var/log/nginx/access.log main if=$loggable;

# 4) 同一级别可写多份日志(例如全量 + 仅错误)
access_log /var/log/nginx/access.log main;
access_log /var/log/nginx/error-only.log main if=$loggable;

# 5) 日志名含变量时,缓存文件描述符
open_log_file_cache max=1000 inactive=20s valid=1m min_uses=2;

要点:

  • buffer/gzip 会缓冲写入,降低 IO 次数,但故障时可能丢最后几条(flush 控制);
  • 路径含变量时不支持缓冲,且每次写都要打开文件,用 open_log_file_cache 缓解;
  • if= 的条件为 0 或空时不记录,可用来做"采样/只记异常"。

五、error_log 级别

1
error_log /var/log/nginx/error.log warn;

级别从低到高:debug → info → notice → warn → error → crit → alert → emerg。生产常用 warn 或 error;排查时临时开到 info/debug,用完记得调回(debug 量极大)。

六、请求耗时分解

$request_time 是黑盒总时长,拆开看才有定位价值:

sequenceDiagram
    participant C as 客户端
    participant N as Nginx
    participant U as 上游
    C->>N: 请求
    Note over N,U: $upstream_connect_time
    N->>U: 建立连接
    Note over N,U: $upstream_header_time
    U-->>N: 响应头
    Note over N,U: $upstream_response_time
    U-->>N: 响应体
    N-->>C: 响应
    Note over N: $request_time
  • $upstream_response_time 大、$upstream_connect_time 小 → 后端处理慢;
  • $upstream_connect_time 大 → 建连慢(网络/上游 accept 队列);
  • $request_time 远大于上游时间 → Nginx 到客户端之间慢(带宽、客户端、响应体大)。

七、实时指标:stub_status 与 exporter

1
2
3
4
5
location = /basic_status {
stub_status;
allow 127.0.0.1;
deny all;
}

输出(需编译 --with-http_stub_status_module):

1
2
3
4
Active connections: 291
server accepts handled requests
16630948 16630948 31070465
Reading: 6 Writing: 179 Waiting: 106
  • Active connections:当前活跃连接(含 Waiting);
  • accepts / handled:接受 / 处理完成的连接数,二者差距通常意味着触达了 worker_connections 限制;
  • requests:总请求数;Reading/Writing/Waiting:读请求头 / 写响应 / 空闲等待。

更完整的指标(连接、请求、SSL 握手、upstream 等)可用社区 nginx-prometheus-exporter 采集 stub_status / Nginx Plus API,交给 Prometheus + Grafana。它只读状态页,不侵入配置。

八、日志轮转与留存

日志文件改名后,Nginx 仍持有旧句柄,需要发 USR1 重开:

1
2
mv /var/log/nginx/access.log /var/log/nginx/access.log.1
nginx -s reopen # = kill -USR1 $(cat /var/run/nginx.pid)

配合 logrotate 时,把 postrotate 写成 nginx -s reopen;留存策略(天数/大小/压缩)交给 logrotate 或采集端。

九、排错

现象原因 / 处理
日志文件里没有新记录未 nginx -s reopen;或 access_log off 覆盖了上级
日志里全是 \xXX用了 default 转义;需要 JSON 就改 escape=json
日志量爆炸静态资源未关日志;加 access_log off 或 if= 条件
上游字段是 -请求没走代理(命中静态/缓存);属正常
时间对不上时区配置不一致;用 $time_iso8601 统一
stub_status 404模块未编译;allow/deny 拦了来源 IP

参考链接

  1. Nginx 官方文档:ngx_http_log_module —— log_format / access_log / open_log_file_cache;
  2. Nginx 官方文档:ngx_http_stub_status_module —— 状态字段含义与 $connections_* 变量;
  3. Nginx 官方文档:ngx_http_core_module($request_id) —— 请求唯一 ID;
  4. Nginx 官方文档:ngx_http_upstream_module($upstream_*) —— 上游相关变量;
  5. Nginx 官方文档:Controlling nginx(USR1 重开日志);
  6. nginx-prometheus-exporter —— 指标接入 Prometheus;
  7. RFC 8259:JSON 字符串转义。

小结

  • access_log 记结果、error_log 记错误、stub_status 记实时状态,三者互补;
  • 用 log_format + escape=json 定义可采集的结构化字段,把 $request_id 带上做全链路;
  • $request_time 要拆成 connect/header/response 三段看,才能分清是后端慢还是链路慢;
  • buffer/flush/if= 用来控量,open_log_file_cache 解决变量路径日志;
  • 日志轮转后 nginx -s reopen;指标用 stub_status + exporter 接入监控。

系列导航


Nginx 工程实践 -- 11. 日志与可观测性
https://bubao.github.io/posts/b1c2d3e4.html
作者
一念
发布于
2026年11月21日
许可协议