linux

nginx日志格式设置指南

小樊
52
2025-09-09 14:10:51
栏目: 编程语言

Nginx日志格式设置指南

一、基础配置步骤

  1. 打开配置文件
    通常位于 /etc/nginx/nginx.conf/etc/nginx/conf.d/*.conf,使用文本编辑器修改:

    sudo nano /etc/nginx/nginx.conf
    
  2. 定义日志格式
    http 块中使用 log_format 指令自定义格式,变量用 $ 开头,常用变量包括:

    • $remote_addr:客户端IP
    • $request:请求行(方法+URI+协议)
    • $status:响应状态码
    • $body_bytes_sent:响应体字节数
    • $request_time:请求处理总时间(秒)
    • $upstream_response_time:后端响应时间(反向代理场景)
    http {
        log_format custom '$remote_addr - $request $status $body_bytes_sent $request_time';
        # 其他配置...
    }
    
  3. 应用日志格式
    serverlocation 块中通过 access_log 指令引用自定义格式:

    server {
        access_log /var/log/nginx/access.log custom;
        # 其他配置...
    }
    
  4. 重启Nginx生效

    sudo nginx -s reload
    

二、常用日志格式示例

  1. 默认格式(combined)

    log_format combined '$remote_addr - $remote_user [$time_local] "$request" '
                       '$status $body_bytes_sent "$http_referer" '
                       '"$http_user_agent" "$http_x_forwarded_for"';
    
  2. JSON格式
    适合日志分析工具(如ELK):

    log_format json '{ "time": "$time_iso8601", "ip": "$remote_addr", "request": "$request", "status": $status }';
    
  3. 带缓冲的格式
    提升高流量场景性能,按指定大小或时间写入磁盘:

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

三、高级配置技巧

  1. 条件日志记录
    通过 map 指令过滤不需要记录的请求(如静态资源):

    map $uri $loggable {
        ~^/static/ 0;
        default 1;
    }
    access_log /var/log/nginx/access.log custom if=$loggable;
    
  2. 多日志文件分离
    按虚拟主机或路径拆分日志:

    server {
        server_name site1.example.com;
        access_log /var/log/nginx/site1.access.log custom;
    }
    
  3. 日志轮转管理
    配合 logrotate 工具避免日志占满磁盘,示例配置:

    # /etc/logrotate.d/nginx
    /var/log/nginx/*.log {
        daily
        rotate 7
        compress
        missingok
        create 0640 www-data adm
        postrotate
            /usr/sbin/nginx -s reload
        endscript
    }
    

四、注意事项

配置参考来源:

0
看了该问题的人还看了