一、日志的作用与原理
1.1 起源
访问日志解决的核心问题:将一次 HTTP 请求的全过程关键事实结构化记录下来,使服务行为可回溯、可统计、可告警。nginx 默认每条请求记录一行,写入由 ngx_http_log_module 完成,发生在请求结束的 log 阶段。
1.2 日志写入机制
- 每个请求在 log 阶段触发一次访问日志写入
- 写入目标由
access_log指令决定,可指向文件、syslog、内存缓冲 - 多个
access_log可同时记录不同格式到不同目标 access_log off;可在某个 location 关闭记录
1.3 格式定义原理
- 格式由
log_format定义,本质是一个由 nginx 变量按顺序拼接的字符串 - 变量在请求处理过程中被求值,log 阶段时取最终值
- 同一请求中未定义的变量记为空(
-)
二、自定义 log_format
2.1 默认 combined 格式
log_format combined '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent"';
access_log /var/log/nginx/access.log combined;
2.2 扩展格式(含响应时间与后端信息)
推荐记录以下字段,便于性能与故障分析:
log_format main '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" '
'$request_time $upstream_response_time '
'$upstream_addr $upstream_cache_status '
'$pipe $connection $connection_requests';
access_log /var/log/nginx/access.log main;
字段含义:
| 变量 | 含义 |
|---|---|
$request_time | 从接收第一个字节到返回响应的整体耗时(秒) |
$upstream_response_time | 后端响应耗时(秒);多个后端用逗号分隔 |
$upstream_addr | 实际命中的后端地址 |
$upstream_cache_status | proxy 缓存命中状态 |
$pipe | p 表示 pipeline 请求,. 表示普通请求 |
$connection | 连接序号 |
$connection_requests | 当前连接上已处理的请求数(长连接复用观察) |
三、JSON 结构化日志
便于日志采集系统(Filebeat / Promtail / Fluentd)直接解析,无需正则切分。
log_format json escape=json '{'
'"remote_addr":"$remote_addr",'
'"time":"$time_iso8601",'
'"method":"$request_method",'
'"uri":"$uri",'
'"args":"$args",'
'"host":"$host",'
'"status":$status,'
'"bytes_sent":$body_bytes_sent,'
'"request_time":$request_time,'
'"upstream_time":"$upstream_response_time",'
'"upstream_addr":"$upstream_addr",'
'"cache_status":"$upstream_cache_status",'
'"referer":"$http_referer",'
'"user_agent":"$http_user_agent",'
'"xff":"$http_x_forwarded_for"'
'}';
access_log /var/log/nginx/access.log json;
说明:
escape=json对值中的特殊字符做 JSON 转义(nginx 1.11.8+)- 数值型字段(
$status、$body_bytes_sent、$request_time)不加引号,便于聚合计算 - 字符串型字段加引号
四、access_log 高级选项
4.1 缓冲写入
access_log /var/log/nginx/access.log main buffer=64k flush=5s;
buffer=64k:写满 64KB 才落盘,减少 IOflush=5s:超过 5 秒强制落盘- 无缓冲则每请求一次 write,高 QPS 下成为瓶颈
4.2 条件日志
# 只记录 4xx/5xx
map $status $loggable {
default 0;
~^[45] 1;
}
access_log /var/log/nginx/access.log main if=$loggable;
# 不记录静态资源与健康检查
location ~* \.(jpg|png|gif|css|js|ico)$ {
access_log off;
}
location = /healthcheck {
access_log off;
}
4.3 多目标记录
# 同时记录全量日志与错误日志
access_log /var/log/nginx/access.log main;
access_log /var/log/nginx/error_only.log main if=$loggable;
# 发送到 syslog
access_log syslog:server=127.0.0.1:514,facility=local7,tag=nginx,severity=info main;
4.4 gzip 压缩日志(实时)
access_log /var/log/nginx/access.log main buffer=64k flush=5s gzip=6;
gzip=6 启用实时压缩落盘,文件为 gzip 格式,分析前需 zcat 解压。
五、日志轮转
nginx 不会自动切割日志文件,长期运行后单个文件过大。使用系统 logrotate。
5.1 logrotate 配置
/etc/logrotate.d/nginx:
/var/log/nginx/access.log /var/log/nginx/error.log {
daily
rotate 30
missingok
notifempty
compress
delaycompress
dateext
dateformat -%Y%m%d
sharedscripts
postrotate
[ -f /run/nginx.pid ] && kill -USR1 `cat /run/nginx.pid`
endscript
}
说明:
daily:每日切割;rotate 30:保留 30 份compress+delaycompress:隔一份再压缩,避免当前写入文件被压postrotate发送USR1信号,nginx 重新打开日志文件描述符(无需 reload)
5.2 容器内轮转
容器内通常无 logrotate,推荐改为标准输出由 docker 日志驱动管理:
docker run -d \
--log-driver json-file \
--log-opt max-size=50m \
--log-opt max-file=10 \
--name nginx nginx:stable
或将容器 /var/log/nginx/ 挂载到宿主机,由宿主机 logrotate 处理。
六、命令行分析
基于标准 access.log,以下命令均可直接运行。
6.1 请求量统计
# 当日 PV(行数)
wc -l /var/log/nginx/access.log
# 每小时请求数
awk '{print substr($4,2,13)}' /var/log/nginx/access.log | sort | uniq -c
# QPS 峰值(按秒聚合取最大)
awk '{print $4}' /var/log/nginx/access.log | cut -c 2-20 | sort | uniq -c | sort -rn | head
6.2 状态码分布
# 状态码计数
awk '{print $9}' /var/log/nginx/access.log | sort | uniq -c | sort -rn
# 5xx 错误请求明细
awk '$9 ~ /^5/ {print}' /var/log/nginx/access.log | tail -20
# 4xx/5xx 占比
awk '{a[$9]++} END {for (k in a) printf "%s: %d (%.2f%%)\n", k, a[k], a[k]/NR*100}' /var/log/nginx/access.log
6.3 来源 IP TOP
# 访问量 TOP 20 IP
awk '{print $1}' /var/log/nginx/access.log | sort | uniq -c | sort -rn | head -20
# TOP IP 对应的请求路径
awk '{ip[$1]++} END {for (k in ip) if (ip[k]>100) print k, ip[k]}' /var/log/nginx/access.log
# 疑似刷量 IP(高频访问同一 URL)
awk '{print $1, $7}' /var/log/nginx/access.log | sort | uniq -c | sort -rn | head -20
6.4 热门 URL
# 访问量 TOP 20 路径
awk '{print $7}' /var/log/nginx/access.log | sort | uniq -c | sort -rn | head -20
# 流量 TOP 20(按字节)
awk '{sum[$7]+=$10} END {for (k in sum) print sum[k], k}' /var/log/nginx/access.log | sort -rn | head -20
6.5 响应时间分析
需使用扩展格式(含 $request_time 在第 10 列为例):
# 平均响应时间
awk '{sum+=$10} END {printf "%.3fs\n", sum/NR}' /var/log/nginx/access.log
# 慢请求 TOP(>1s)
awk '$10>1 {print $10, $7, $1}' /var/log/nginx/access.log | sort -rn | head -20
# 响应时间分布(P50/P95/P99)
awk '{a[NR]=$10} END {
n=asort(a);
printf "P50=%.3f P95=%.3f P99=%.3f\n", a[int(n*0.5)], a[int(n*0.95)], a[int(n*0.99)]
}' /var/log/nginx/access.log
6.6 后端健康度
# upstream 响应时间分布
awk '{print $11}' /var/log/nginx/access.log | sort -n | tail -20
# 命中各后端的次数
awk '{print $12}' /var/log/nginx/access.log | sort | uniq -c
# 缓存命中率
awk '{print $13}' /var/log/nginx/access.log | sort | uniq -c
6.7 时间段过滤
# 提取 14:00-15:00 的请求
awk '$4 ~ /\[18\/Aug\/2026:14:/' /var/log/nginx/access.log | wc -l
# 指定日期的 5xx
awk '$4 ~ /18\/Aug\/2026/ && $9 ~ /^5/ {print}' /var/log/nginx/access.log
七、实时终端监控
7.1 实时 tail 统计
# 实时状态码分布(每秒刷新)
tail -f /var/log/nginx/access.log | awk '{a[$9]++; print}'
# 实时 QPS(每秒请求计数)
tail -f /var/log/nginx/access.log | stdbuf -oL awk '
{ts=substr($4,2,20); c[ts]++}
{print ts, c[ts]}'
# 实时慢请求告警(>2s 输出)
tail -f /var/log/nginx/access.log | awk '$10>2 {print strftime("%H:%M:%S"), $0}'
7.2 在线请求观察(pv/uv)
# 每 10 秒输出一次 QPS
tail -f /var/log/nginx/access.log | while read line; do
now=$(date +%s)
count=$(tail -n 1000 /var/log/nginx/access.log | wc -l)
echo "$now count=$count"
done
八、日志分析工具
8.1 GoAccess(实时终端 + HTML 报告)
开源、轻量,支持实时终端分析与离线 HTML 报告生成。
# 安装
apt install goaccess
# 实时终端分析
goaccess /var/log/nginx/access.log --log-format=COMBINED
# 指定扩展格式(含 request_time)
goaccess /var/log/nginx/access.log --log-format='%h %^ %^ [%d:%t %^] "%r" %s %b "%R" "%u" %T %D'
# 生成 HTML 报告
goaccess /var/log/nginx/access.log \
--log-format=COMBINED \
--real-time-html \
-o /usr/share/nginx/html/report.html
实时模式监听文件变化,HTML 报告可通过浏览器访问持续刷新。
8.2 ELK 栈
Filebeat 采集 -> Logstash/ES -> Kibana 可视化。
# filebeat.yml
filebeat.inputs:
- type: log
paths:
- /var/log/nginx/access.log
json.message_key: remote_addr
json.keys_under_root: true
output.elasticsearch:
hosts: ["elasticsearch:9200"]
适合大规模、长期存储、复杂查询聚合场景。
8.3 Loki + Grafana
轻量级替代方案,Promtail 采集 -> Loki 存储 -> Grafana 展示。
# promtail.yml
scrape_configs:
- job_name: nginx
static_configs:
- targets: [localhost]
labels:
job: nginx
__path__: /var/log/nginx/*.log
pipeline_stages:
- json:
expressions:
status: status
request_time: request_time
uri: uri
成本低于 ELK,适合只索引标签不索引全文的场景。
九、在线监控指标方案
9.1 stub_status 内置状态页
location /nginx_status {
stub_status on;
access_log off;
allow 127.0.0.1;
allow 10.0.0.0/8;
deny all;
}
输出:
Active connections: 15
server accepts handled requests
8456 8456 32891
Reading: 0 Writing: 3 Waiting: 12
字段含义:
| 字段 | 含义 |
|---|---|
| Active connections | 当前活跃连接数 |
| accepts | 已接受连接总数 |
| handled | 已处理连接总数 |
| requests | 已处理请求总数 |
| Reading | 正在读取请求头的连接数 |
| Writing | 正在返回响应的连接数 |
| Waiting | 空闲等待中的长连接数 |
指标解读:
Waiting占比高说明长连接复用好Reading持续偏高说明客户端上传慢或请求体大accepts - handled长期为正表示存在连接建立失败(资源耗尽)
9.2 Prometheus + nginx_exporter
采集 stub_status 与日志指标,接入 Prometheus。
# prometheus.yml
scrape_configs:
- job_name: nginx
static_configs:
- targets: ['nginx_exporter:9113']
常用 exporter:
nginx/nginx-prometheus-exporter:采集 stub_status(连接数、请求数)martin-helmich/nginx-prometheus-exporter:支持更多自定义指标
采集到的指标示例:
| 指标 | 含义 |
|---|---|
nginx_connections_active | 活跃连接数 |
nginx_connections_reading | 读取中连接数 |
nginx_connections_writing | 写入中连接数 |
nginx_connections_waiting | 等待中连接数 |
nginx_http_requests_total | 请求总数(counter) |
nginx_up | nginx 存活状态 |
9.3 日志指标导出(基于 mtail / promtail)
从 access.log 解析生成 Prometheus 指标(QPS、状态码分布、响应时间分位)。
# /etc/mtail/nginx.mtail
counter nginx_requests by status
histogram nginx_request_time buckets 0.01, 0.05, 0.1, 0.5, 1, 5
/^(?P<ip>\S+) .* \[(?P<ts>.*?)\] "(?P<method>\S+) (?P<uri>\S+).*" (?P<status>\d+) \d+ ".*" ".*" (?P<rt>[\d.]+)$/ {
nginx_requests[status]++
nginx_request_time = $rt
}
mtail -progs /etc/mtail/nginx.mtail -logs /var/log/nginx/access.log -port 3903
适合采集 stub_status 无法覆盖的业务级指标(4xx/5xx 比例、P95 延迟)。
9.4 nginx_vts_module(虚拟主机流量统计)
第三方模块,按 server/location 维度统计请求数、流量、响应时间、缓存命中率。
http {
vhost_traffic_status_zone;
server {
location /status {
vhost_traffic_status_display;
vhost_traffic_status_display_format html;
}
}
}
访问 /status 可查看按虚拟主机分维度的实时统计面板,也可输出 JSON 供采集。
9.5 Grafana 看板维度建议
| 维度 | 指标 | 观测目的 |
|---|---|---|
| 流量 | QPS / PV / 带宽 | 容量规划 |
| 可用性 | 5xx 比例 / 5xx 速率 | 故障告警 |
| 性能 | P50 / P95 / P99 响应时间 | 性能退化监测 |
| 后端 | upstream 响应时间 / 失败率 | 后端健康度 |
| 缓存 | cache hit / miss 比例 | 缓存策略有效性 |
| 连接 | active / waiting / dropped | 连接资源占用 |
| 安全 | 401/403/429 速率 | 异常访问探测 |
9.6 告警示例(Prometheus Alertmanager)
groups:
- name: nginx
rules:
- alert: NginxHigh5xxRate
expr: |
sum(rate(nginx_http_requests_total{status=~"5.."}[5m]))
/ sum(rate(nginx_http_requests_total[5m])) > 0.05
for: 5m
labels:
severity: critical
annotations:
summary: "nginx 5xx 比例超过 5%"
- alert: NginxDown
expr: nginx_up == 0
for: 1m
labels:
severity: critical
annotations:
summary: "nginx 实例不可达"
- alert: NginxHighLatency
expr: |
histogram_quantile(0.95,
rate(nginx_request_time_bucket[5m])) > 2
for: 5m
labels:
severity: warning
annotations:
summary: "P95 响应时间超过 2s"
十、分析流程速查
定位问题的典型分析路径:
- 看
nginx_up与 stub_status 确认服务存活与连接状态 - 用状态码分布确认是否大面积 5xx
- 用慢请求 TOP 定位瓶颈 URL
- 用
$upstream_addr+$upstream_response_time判断是 nginx 自身慢还是后端慢 - 用缓存命中率确认是否缓存失效导致回源压力
- 用来源 IP TOP 判断是否异常流量需触发限流
- 用时间段过滤还原故障时刻的请求序列
十一、完整配置示例
以下为开启访问日志与错误日志的完整可用配置,含 combined / main / json 三种格式定义,默认启用 main。main 采用 rt=/urt=/ua=/cs= 带标签写法,便于 grep 与 GoAccess 适配(见 GoAccess 日志分析 4.3 节),与第二章 2.2 裸字段写法等价。
# /etc/nginx/nginx.conf
# 开启访问日志 + 错误日志的完整可用配置
# 三种 log_format(combined / main / json),默认启用 main
# 挂载方式:
# docker run -d -p 80:80 \
# -v /host/nginx.conf:/etc/nginx/nginx.conf:ro \
# -v /host/logs:/var/log/nginx \
# --name nginx nginx:stable
# ========= main 上下文 =========
user nginx;
worker_processes auto;
worker_rlimit_nofile 65535;
# 错误日志:warn 及以上级别写入
error_log /var/log/nginx/error.log warn;
pid /run/nginx.pid;
events {
worker_connections 1024;
use epoll;
multi_accept on;
}
http {
include /etc/nginx/mime.types;
default_type application/octet-stream;
sendfile on;
tcp_nopush on;
keepalive_timeout 65;
# ========= 日志格式定义 =========
# combined:nginx 默认格式
log_format combined '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent"';
# main:扩展格式,含响应时间与后端信息(推荐用于排查)
log_format main '$remote_addr - $remote_user [$time_local] '
'"$request" $status $body_bytes_sent '
'"$http_referer" "$http_user_agent" '
'rt=$request_time urt=$upstream_response_time '
'ua=$upstream_addr cs=$upstream_cache_status';
# json:结构化格式(供 Filebeat/Promtail 直接解析)
log_format json escape=json '{'
'"remote_addr":"$remote_addr",'
'"time_local":"$time_local",'
'"method":"$request_method",'
'"uri":"$uri",'
'"args":"$args",'
'"host":"$host",'
'"status":$status,'
'"bytes_sent":$body_bytes_sent,'
'"request_time":$request_time,'
'"upstream_time":"$upstream_response_time",'
'"upstream_addr":"$upstream_addr",'
'"cache_status":"$upstream_cache_status",'
'"referer":"$http_referer",'
'"user_agent":"$http_user_agent",'
'"xff":"$http_x_forwarded_for"'
'}';
# ========= 开启访问日志 =========
# 默认启用 main 格式;缓冲 64KB、每 5 秒落盘,降低 IO 压力
access_log /var/log/nginx/access.log main buffer=64k flush=5s;
# 如需 JSON 格式,注释掉上一行,启用下一行
# access_log /var/log/nginx/access.json json buffer=64k flush=5s;
# ========= server =========
server {
listen 80;
server_name localhost;
root /usr/share/nginx/html;
index index.html index.htm;
# 显式继承 http 层日志配置(默认即生效,写出来便于确认)
access_log /var/log/nginx/access.log main;
location / {
try_files $uri $uri/ =404;
}
# 健康检查:关闭日志,避免刷屏
location = /healthcheck {
access_log off;
return 200 'ok';
add_header Content-Type text/plain;
}
# 静态资源:可选关闭日志降噪
# location ~* \.(jpg|png|gif|css|js|ico)$ {
# access_log off;
# expires 30d;
# }
}
}
main 格式输出示例:
172.17.0.1 - - [18/Aug/2026:10:12:33 +0000] "GET / HTTP/1.1" 200 612 "-" "curl/7.81.0" rt=0.001 urt=- ua=- cs=-
生效与验证:
nginx -t
nginx -s reload
curl -I http://localhost/
tail -f /var/log/nginx/access.log
健康检查 /healthcheck 已关闭日志,避免频繁刷屏。原独立配置文件已并入本章,不再单独维护。