全部学科
Python全栈
python
NodeJS全栈
nodejs
小程序首页
📅 2026-05-20 6 分钟 ✍️ juanwangdev

日志优化与缓冲

默认情况下 NGINX 每条日志都同步写入磁盘。高流量场景下日志 I/O 可占总 I/O 的 20%-30%。缓冲和格式优化可显著降低开销。

日志缓冲

启用缓冲

nginx
http {
    access_log /var/log/nginx/access.log combined buffer=16m flush=60s;
}
  • buffer=16m — 日志先写入 16MB 缓冲区
  • flush=60s — 每 60 秒强制刷新一次
  • 缓冲区满时自动刷盘

缓冲日志可减少 30%-50% 的磁盘 I/O。缓冲区越大 I/O 效率越高,但崩溃时可能丢失未刷新的日志。

多日志流分离

按业务分离

nginx
http {
    # 主访问日志(带缓冲)
    access_log /var/log/nginx/access.log combined buffer=16m;
    
    server {
        # API 单独记录
        location /api/ {
            access_log /var/log/nginx/api_access.log api_format buffer=8m;
            proxy_pass http://backend;
        }
        
        # 静态资源可关闭日志
        location /static/ {
            access_log off;
        }
    }
}

静态资源流量大但价值低,可关闭日志或使用采样日志。API 日志单独存储便于独立分析。

采样日志

仅记录部分请求

nginx
http {
    map $request_id $log_sample {
        default 0;
        ~^[0-9a-f] 1;  # 约 1/16 的请求
    }
    
    server {
        access_log /var/log/nginx/access.log;
        access_log /var/log/nginx/sampled_access.log combined if=$log_sample;
    }
}

JSON 格式日志

结构化输出

nginx
log_format json escape=json
    '{"time":"$time_iso8601",'
    '"remote_addr":"$remote_addr",'
    '"request_method":"$request_method",'
    '"uri":"$uri",'
    '"status":$status,'
    '"body_bytes_sent":$body_bytes_sent,'
    '"request_time":$request_time,'
    '"upstream_time":"$upstream_response_time",'
    '"user_agent":"$http_user_agent"}';

access_log /var/log/nginx/access.json.log json buffer=16m;

JSON 格式便于 ELK、Fluentd 等日志系统直接解析,无需额外转换。escape=json 确保特殊字符正确转义。

自定义字段

记录业务相关信息

nginx
log_format detailed
    '$remote_addr - $remote_user [$time_local] '
    '"$request" $status $body_bytes_sent '
    '"$http_referer" "$http_user_agent" '
    'rt=$request_time uct=$upstream_connect_time '
    'urt=$upstream_response_time uct=$upstream_response_time '
    'cs=$upstream_cache_status';

常用性能相关变量:

  • $request_time — 请求总处理时间
  • $upstream_connect_time — 连接上游时间
  • $upstream_response_time — 上游响应时间
  • $upstream_cache_status — 缓存命中状态

日志轮转

logrotate 优化

text
/var/log/nginx/*.log {
    daily
    rotate 30
    compress
    delaycompress
    missingok
    notifempty
    create 0640 www-data adm
    sharedscripts
    postrotate
        [ -f /var/run/nginx.pid ] && kill -USR1 $(cat /var/run/nginx.pid)
    endscript
}

delaycompress 延迟一天压缩,方便查看昨日未压缩日志。sharedscripts 保证多个日志文件只执行一次 postrotate。

要点总结

  • 使用 bufferflush 参数减少日志磁盘 I/O
  • 高流量静态资源可关闭日志或使用采样
  • JSON 格式日志便于日志聚合系统解析
  • 按业务分离日志流便于独立分析和告警
  • 自定义格式记录响应时间和上游状态便于性能分析
  • logrotate 配合 USR1 信号实现无缝日志轮转

📝 发现内容有误?点击此处直接编辑

← 上一篇 事件驱动模型优化
下一篇 → 系统内核参数调优
想查看更多题目和详细解析?
小程序提供完整的题库、模拟考试和详细解析
马上就来

长按或扫描二维码,立即体验

扫码体验小程序
马上就来
使用微信扫描二维码
立即体验完整题库