全书目录

第十七篇:Nginx 完全指南 —— 城市总闸口宇宙

第十一章:日志 —— 过车记录看 access_log,事故记录看 error_log

1 分钟 230 字 第 331 / 962 个阅读单元

没有日志,城市总闸口一出事,你只会看到一句“502”。

Nginx 最基本的两种日志:

  • access_log:谁来了、请求了什么、返回多少、耗时如何
  • error_log:配置错误、上游失败、文件找不到、模块报错

可以先配一个足够实用的访问日志格式:

nginx
http {
    log_format main escape=json
        '{'
            '"time":"$time_iso8601",'
            '"remote_addr":"$remote_addr",'
            '"request":"$request",'
            '"status":$status,'
            '"body_bytes_sent":$body_bytes_sent,'
            '"request_time":$request_time,'
            '"upstream_addr":"$upstream_addr",'
            '"upstream_status":"$upstream_status",'
            '"upstream_response_time":"$upstream_response_time",'
            '"http_referer":"$http_referer",'
            '"http_user_agent":"$http_user_agent"'
        '}';

    access_log /var/log/nginx/access.log main;
    error_log  /var/log/nginx/error.log warn;
}

这相当于总闸口的两套记录系统:

text
access_log -> 过车流水
error_log  -> 故障与事故登记

排查问题时,大致这么看:

text
用户说打不开
-> 先看 access_log 是否收到请求
-> 再看 status 是 404 / 499 / 502 / 504 哪一种
-> 再看 error_log 有没有 upstream、permission、not found 等错误

典型含义:

  • 404:路径没命中,或文件真不存在
  • 502:Nginx 去找后端,后端没正常响应
  • 504:后端太慢,闸口等超时了
  • 499:客户端自己先断开了