插件窝 干货文章 Nginx如何自定义记录及启用日志缓冲区

Nginx如何自定义记录及启用日志缓冲区

Nginx log 缓冲区 配置 513    来源:    2025-04-25

Nginx日志自定义与缓冲区配置指南

自定义日志记录

1. 自定义日志格式

在Nginx配置文件中(通常位于/etc/nginx/nginx.conf),可以使用log_format指令定义自定义日志格式:

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

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

常用变量说明: - $remote_addr - 客户端IP地址 - $remote_user - 认证用户名 - $time_local - 本地时间 - $request - 请求行(GET/POST等) - $status - 响应状态码 - $body_bytes_sent - 发送给客户端的字节数 - $http_referer - 来源页面 - $http_user_agent - 客户端浏览器信息 - $request_time - 请求处理时间(秒) - $upstream_response_time - 后端服务器响应时间

2. 多日志文件配置

可以为不同server或location配置不同的日志文件:

server {
    listen 80;
    server_name example.com;

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

    location /api {
        access_log /var/log/nginx/api.access.log custom_log;
        # API相关配置
    }
}

启用日志缓冲区

1. 基本缓冲区配置

access_log /var/log/nginx/access.log custom_log buffer=64k flush=5m;

参数说明: - buffer=size - 设置缓冲区大小(默认64k) - flush=time - 设置缓冲区刷新时间(默认60秒)

2. 高级缓冲区配置

access_log /var/log/nginx/access.log custom_log 
    buffer=256k 
    flush=1m 
    gzip=1 
    if=$loggable;

附加参数: - gzip=level - 启用gzip压缩(1-9压缩级别) - if=condition - 条件日志记录

3. 系统级优化

对于高流量网站,还可以考虑:

  1. 调整内核参数增加文件描述符限制
  2. 使用open_log_file_cache缓存日志文件描述符:
open_log_file_cache max=1000 inactive=20s valid=1m min_uses=2;

最佳实践建议

  1. 缓冲区大小选择

    • 低流量站点:32k-64k
    • 中等流量:128k-256k
    • 高流量:512k-1m
  2. 刷新间隔

    • 生产环境:1-5分钟
    • 调试环境:可设置更短
  3. 日志轮转: 配置logrotate定期轮转日志文件,示例配置(/etc/logrotate.d/nginx):

    /var/log/nginx/*.log {
       daily
       missingok
       rotate 14
       compress
       delaycompress
       notifempty
       create 0640 www-data adm
       sharedscripts
       postrotate
           /usr/sbin/nginx -s reopen
       endscript
    }
    
  4. 性能监控

    • 监控磁盘I/O使用情况
    • 检查Nginx worker进程的CPU和内存使用

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

sudo nginx -t && sudo nginx -s reload