nginx 开启日志,记录客户端请求的接口、时间、耗时、ip等等信息

784 阅读2分钟

要在 Nginx 中开启日志并记录客户端请求的详细信息,包括接口、时间、耗时、IP 等,可以通过配置 Nginx 的日志格式和日志文件来实现。以下是具体的步骤:

要在 Nginx 中开启日志并记录客户端请求的详细信息,包括接口、时间、耗时、IP 等,可以通过配置 Nginx 的日志格式和日志文件来实现。以下是具体的步骤:

1. 定义自定义日志格式

在 Nginx 配置文件中(通常是 /etc/nginx/nginx.conf 或站点的配置文件),定义一个自定义日志格式。例如:

http {
    log_format custom_format '$remote_addr - $remote_user [$time_local] '
                             '"$request" $status $body_bytes_sent '
                             '"$http_referer" "$http_user_agent" '
                             '$request_time $upstream_response_time '
                             '$host $uri $args';

    access_log /var/log/nginx/access.log custom_format;
    ...
}

2. 日志字段说明

  • $remote_addr:客户端 IP 地址。
  • $remote_user:客户端认证用户名(如果有)。
  • $time_local:请求时间。
  • $request:请求的完整内容(方法、路径和协议)。
  • $status:HTTP 状态码。
  • $body_bytes_sent:发送给客户端的字节数。
  • $http_referer:来源页面。
  • $http_user_agent:客户端的 User-Agent 信息。
  • $request_time:请求处理的总时间。
  • $upstream_response_time:后端响应时间(如果有反向代理)。
  • $host:请求的主机名。
  • $uri:请求的 URI。
  • $args:请求参数。

3. 启用日志

确保你在 server 块或 location 块中启用了 access_log 指令。例如:

server {
    listen 80;
    server_name example.com;

    access_log /var/log/nginx/example_access.log custom_format;

    location / {
        root /var/www/html;
        index index.html;
    }
}

4. 重新加载 Nginx

修改配置后,检查配置语法是否正确并重新加载 Nginx:

nginx -t
sudo systemctl reload nginx

5. 查看日志

日志文件会记录在你配置的路径中,例如 /var/log/nginx/access.log。可以使用以下命令实时查看日志:

tail -f /var/log/nginx/access.log

通过以上配置,你可以详细记录每个请求的接口、时间、耗时、IP 等关键信息,方便后续分析和调试。

仅在 http模块,开启 access_log,也可以

仅在 http 模块中开启全局的 access_log 确实可以记录所有请求的日志,不需要在每个 serverlocation 块中单独配置。这种方式适合全局日志管理,但要注意以下几点:

  1. 全局启用 access_log 的配置方法
    http 模块中直接设置日志格式和日志路径。例如:

    http { log_format custom_format 'remoteaddrremote_addr - remote_user [time_local] ' '"request" statusstatus body_bytes_sent ' '"httpreferer""http_referer" "http_user_agent" ' 'requesttimerequest_time upstream_response_time ' 'hosthost uri $args';

    access_log /var/log/nginx/access.log custom_format;
    
    include /etc/nginx/conf.d/*.conf;
    

    }

在这种情况下,所有的请求日志都会按照定义的 custom_format 写入到 /var/log/nginx/access.log

  1. 控制日志记录的粒度
    如果仅在 http 模块中配置了全局的 access_log,可以通过以下方式控制哪些请求被记录:

    • 特定路径的日志关闭:在 serverlocation 块中禁用日志:

      server {
          access_log off;
          ...
      }
      
    • 按条件记录日志:通过 if 条件动态控制日志记录,例如仅记录特定状态码的请求:

      map $status $loggable {
          ~^[23] 0;
          default 1;
      }
      
      access_log /var/log/nginx/access.log custom_format if=$loggable;
      
  2. 优点和注意事项

  • 优点:在 http 模块中统一配置日志格式和路径,简化管理,适用于需要全局日志记录的情况。
  • 注意事项:如果服务器的负载较高,全局记录可能会增加磁盘 I/O 和性能开销,建议根据需要启用或优化日志记录。

如果你需要更细粒度的控制,可以结合 serverlocation 的日志设置。全局日志适合统一分析和管理,但在大规模生产环境中可能需要优化或分片记录。