配置格式

  1. access_log log_file log_format;

以下是 Nginx 访问日志的默认配置

  1. log_format combined '$remote_addr - $remote_user [$time_local] '
  2. '"$request" $status $body_bytes_sent '
  3. '"$http_referer" "$http_user_agent"';
  4. access_log logs/access.log combined;

变量解释

默认配置的变量

combined 是系统预定义的日志格式,可根据需要自定义,但是名称不能重复。

  1. log_format main '$request_time ...'

日志中各变量的含义

  • remote_addr 客户端 IP 地址。一般 addr 表示 IP, server_name 表示域名。
  • remote_user user name supplied with the Basic authentication
  • time_local local time in the Common Log Format. 服务器的本地时间,会带有时区信息
  • request full original request line. HTTP 请求行
  • status response status, HTTP 响应状态码
  • body_bytes_sent number of bytes sent to a client, not counting the response header; 而 bytes_sent 包含 HTTP 响应的头部信息。
  • http_referer 来源地址
  • http_user_agent 用户代理字符串

    其他有用的变量

    有时需要收集更多的访问信息,你可能自定义日志格式,并加入所需的变量。

  • request_length request length (including request line, header, and request body)

  • request_time request processing time in seconds with a milliseconds resolution; time elapsed between the first bytes were read from the client and the log write after the last bytes were sent to the client
  • http_host HTTP 请求的 host

    日志示例

    请求

    1. curl http://suhua@localhost/index.html \
    2. -H "Referer: http://example.com" \
    3. -H "User-Agent: Mozilla/5.0"

    日志

    1. 192.168.0.1 - suhua [06/Sep/2020:11:46:39 +0800] "GET /index.html HTTP/1.1" 200 9 "http://example.com" "Mozilla/5.0"

    配置示例

    记录上游的响应时间

    1. log_format upstream_time '$remote_addr - $remote_user [$time_local] '
    2. '"$request" $status $body_bytes_sent '
    3. '"$http_referer" "$http_user_agent"'
    4. 'rt=$request_time uct="$upstream_connect_time" uht="$upstream_header_time" urt="$upstream_response_time"';

    配置成 json 格式的日志,可方便后续的分析,在添加新字段时也不需要修改日志解析规则。

    1. log_format json_log escape=json '{"ip": "$remote_addr", "timestamp": "$time_iso8601", '
    2. '"host": "http_host", "request": "$request", '
    3. '"cookie": "$http_cookie", "req_time": "$request_time", '
    4. '"uri": "$uri", "referer": "$http_referer" }';

    注意事项

    配置继承和覆盖

    无论是 error_log 还是 access_log,子配置都会覆盖父配置,如子域中没有配置时才会使用父配置。
    以下配置,access.log 会没有日志,只有 foo-access.log 才有日志。

    1. http {
    2. error_log /var/log/nginx/error.log;
    3. access_log /var/log/nginx/access.log;
    4. server {
    5. error_log /var/log/nginx/foo-error.log;
    6. access_log /var/log/nginx/foo-access.log;
    7. }
    8. }

    参考

  1. 5.1 Request-Line part of Hypertext Transfer Protocol — HTTP/1.1
  2. SP Char in HTTP Headers?
  3. Module ngx_http_log_module
  4. Embedded Variables
  5. Configuring Logging