插件窝 干货文章 nginx怎么配置日志

nginx怎么配置日志

日志 Nginx log access 319    来源:    2025-04-07

Nginx日志配置指南

Nginx提供了灵活的日志配置选项,主要包括访问日志(access_log)和错误日志(error_log)。以下是详细的配置方法:

1. 基本日志配置

访问日志配置

http {
    # 定义日志格式
    log_format main '$remote_addr - $remote_user [$time_local] '
                   '"$request" $status $body_bytes_sent '
                   '"$http_referer" "$http_user_agent" "$http_x_forwarded_for"';

    # 设置访问日志路径和格式
    access_log /var/log/nginx/access.log main;
}

错误日志配置

error_log /var/log/nginx/error.log warn;  # warn级别及以上会记录

2. 高级日志配置选项

按虚拟主机分离日志

server {
    listen 80;
    server_name example.com;

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

按条件记录日志

# 只记录状态码为4xx和5xx的请求
map $status $loggable {
    ~^[23]  0;
    default 1;
}

server {
    access_log /var/log/nginx/error_requests.log main if=$loggable;
}

日志缓冲和压缩

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

3. 常用日志变量

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 - 后端服务器响应时间

4. 日志轮转配置

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

创建/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
}

5. 性能优化建议

  1. 对于高流量网站,考虑:

    • 使用日志缓冲(buffer参数)
    • 减少日志记录频率(如只记录错误请求)
    • 使用syslog直接发送日志到远程服务器
  2. 生产环境建议将日志级别设置为warnerror,避免记录过多调试信息

  3. 定期检查日志文件大小并实施轮转策略

6. JSON格式日志示例

现代日志分析工具通常偏好JSON格式:

log_format json_combined 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"'
    '}';

access_log /var/log/nginx/access.json json_combined;

通过以上配置,您可以灵活地控制Nginx的日志记录行为,满足不同场景下的需求。