溫馨提示×

nginx日志格式設置指南

小樊
53
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
    }
    

四、注意事項

  • 權限設置:確保日志目錄權限正確(如 chown -R www-data:www-data /var/log/nginx)。
  • 敏感信息過濾:避免記錄密碼、Token等敏感字段,可通過變量替換或正則過濾。
  • 性能優化:高流量場景建議啟用緩沖(buffer)或異步寫入(如通過管道輸出到遠程服務器)。

配置參考來源:

0
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女