插件窝 干货文章 如何配置Nginx日志记录详细信息

如何配置Nginx日志记录详细信息

Nginx 日志 配置 记录 208    来源:    2025-05-05

配置Nginx日志记录详细信息

Nginx提供了灵活的日志记录功能,可以通过配置记录详细的访问信息。以下是配置详细日志记录的方法:

1. 配置访问日志(access_log)

在nginx.conf或站点配置文件中,可以自定义访问日志格式:

http {
    log_format detailed '$remote_addr - $remote_user [$time_local] '
                        '"$request" $status $body_bytes_sent '
                        '"$http_referer" "$http_user_agent" '
                        '$request_time $upstream_response_time '
                        '$upstream_addr $upstream_status '
                        '$ssl_protocol $ssl_cipher '
                        '"$http_x_forwarded_for"';

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

2. 配置错误日志(error_log)

error_log /var/log/nginx/error.log warn;

日志级别可选: - debug (最详细) - info - notice - warn - error - crit - alert - emerg (最少信息)

3. 常用日志变量说明

变量 描述
$remote_addr 客户端IP地址
$remote_user 认证用户名
$time_local 本地时间
$request 完整的请求行(GET / HTTP/1.1)
$status 响应状态码
$body_bytes_sent 发送给客户端的字节数
$http_referer 请求来源页面
$http_user_agent 客户端浏览器信息
$http_x_forwarded_for 代理服务器IP链
$request_time 请求处理时间(秒)
$upstream_response_time 后端服务器响应时间
$upstream_addr 后端服务器地址
$upstream_status 后端服务器响应状态码
$ssl_protocol SSL协议版本
$ssl_cipher 使用的加密套件

4. 高级日志配置

按条件记录日志

map $status $loggable {
    ~^[23]  0;  # 不记录2xx和3xx响应
    default 1;   # 记录其他响应
}

access_log /var/log/nginx/error_requests.log combined if=$loggable;

记录POST请求体

默认情况下Nginx不记录POST请求体,如需记录需要额外配置:

log_format postdata '$remote_addr - $remote_user [$time_local] '
                    '"$request" $status $body_bytes_sent '
                    '"$http_referer" "$http_user_agent" '
                    '"$request_body"';

server {
    location / {
        access_log /var/log/nginx/postdata.log postdata;
        # 其他配置...
    }
}

5. 日志轮转

建议设置日志轮转以防止日志文件过大:

# /etc/logrotate.d/nginx
/var/log/nginx/*.log {
    daily
    missingok
    rotate 14
    compress
    delaycompress
    notifempty
    create 0640 www-data adm
    sharedscripts
    postrotate
        /etc/init.d/nginx reload > /dev/null
    endscript
}

6. 最佳实践

  1. 生产环境避免使用debug级别,会产生大量日志
  2. 敏感信息(如密码)不应记录在日志中
  3. 定期检查和分析日志文件
  4. 考虑使用日志分析工具(如ELK、GoAccess)处理大量日志

配置完成后,记得测试并重新加载Nginx配置:

nginx -t && nginx -s reload