插件窝 干货文章 Nginx 日志格式的实现

Nginx 日志格式的实现

日志 Nginx log 格式 196    来源:    2025-04-01

Nginx 日志格式实现指南

Nginx 提供了灵活的日志记录功能,允许管理员自定义日志格式以满足不同的监控、分析和安全需求。以下是关于 Nginx 日志格式实现的详细说明。

1. 日志格式配置基础

Nginx 使用 log_format 指令定义日志格式,然后在 access_logerror_log 指令中应用这些格式。

基本语法

log_format format_name 'string with variables';
access_log /path/to/logfile.log format_name;

2. 预定义日志变量

Nginx 提供了大量内置变量可用于日志格式:

  • $remote_addr - 客户端IP地址
  • $remote_user - 客户端用户名(用于基本认证)
  • $time_local - 本地时间
  • $request - 完整的原始请求行
  • $status - 响应状态码
  • $body_bytes_sent - 发送给客户端的字节数(不包含头)
  • $http_referer - 请求来源页
  • $http_user_agent - 客户端浏览器信息
  • $http_x_forwarded_for - 代理服务器IP链
  • $request_time - 请求处理时间(秒)
  • $upstream_response_time - 上游服务器响应时间

3. 常用日志格式示例

组合日志格式(类似Apache)

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

包含响应时间的扩展格式

log_format extended '$remote_addr - $remote_user [$time_local] '
                   '"$request" $status $body_bytes_sent '
                   '"$http_referer" "$http_user_agent" '
                   'rt=$request_time uct="$upstream_connect_time" uht="$upstream_header_time" urt="$upstream_response_time"';

JSON 格式日志

log_format json_log escape=json
    '{'
        '"time_local":"$time_local",'
        '"remote_addr":"$remote_addr",'
        '"remote_user":"$remote_user",'
        '"request":"$request",'
        '"status": "$status",'
        '"body_bytes_sent":"$body_bytes_sent",'
        '"request_time":"$request_time",'
        '"http_referrer":"$http_referer",'
        '"http_user_agent":"$http_user_agent"'
    '}';

4. 条件日志记录

可以基于条件记录日志:

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

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

5. 日志缓冲和压缩

为提高性能,可以启用日志缓冲和即时压缩:

access_log /var/log/nginx/access.log combined buffer=32k gzip flush=5m;

6. 多日志文件

可以为不同虚拟主机或位置设置不同的日志文件:

server {
    server_name example.com;
    access_log /var/log/nginx/example.com.access.log combined;
    error_log /var/log/nginx/example.com.error.log;

    location /api {
        access_log /var/log/nginx/api.access.log json_log;
    }
}

7. 日志轮转

建议使用 logrotate 管理日志轮转,创建 /etc/logrotate.d/nginx

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

8. 最佳实践

  1. 结构化日志:考虑使用JSON格式便于日志分析工具处理
  2. 敏感信息:避免记录敏感数据如密码、令牌等
  3. 性能考虑:在高流量站点上,评估日志记录对性能的影响
  4. 监控:设置日志监控以检测异常模式
  5. 保留策略:根据合规要求制定适当的日志保留策略

通过灵活配置Nginx日志格式,您可以获得关于服务器性能和用户行为的宝贵见解,同时满足安全和合规要求。