nginx自定義log_format以及輸出自定義http頭


官方文檔地址:

http://nginx.org/en/docs/http/ngx_http_log_module.html

一、log_format默認格式 

首先Nginx默認的log_format的格式為:

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

 

二、自定義多個log_format

上面的main標識給log_format取的別名,比如我可以首先定義多個log_format,例如下面的nginx.conf,我就定義了兩個log_format,一個別名叫yuedu,一個別名叫default

http
    {
        include       mime.types;
        #include luawaf.conf;

        include proxy.conf;
  
        log_format yuedu '$http_yd_uid $http_yd_token $remote_addr [$time_local] $request_method $http_host $request_uri $status $body_bytes_sent $upstream_response_time "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"';
        log_format default '$remote_addr - $remote_user [$time_local] "$request" ' '$status $body_bytes_sent "$http_referer" ' '"$http_user_agent" "$http_x_forwarded_for"';
  
        default_type  application/octet-stream;
        ......
        include /www/server/panel/vhost/nginx/*.conf;
}

  

三、給web網站分配log_format

在nginx里面新建web站點的時候,可以配置該站點使用的log_format格式,如果不指定log_format,則使用的默認的log_format,如下面這個站點使用是別名為yuedu的log_format

access_log  /www/wwwlogs/xxx.log yuedu;
server
{
    listen 80;
    
    server_name www.xxx.com;
    index index.php index.html index.htm default.php default.htm default.html;
    root /www/wwwroot/xxx;
  
    ......
    access_log  /www/wwwlogs/xxx.log yuedu;
    error_log  /www/wwwlogs/xxx.error.log;
}

  

四、access_log里打印自定義的消息header頭

比如現在客戶端在http請求里,加入一個新的自定義的header

Yd-Token : 123465

那么在log_format里要打印輸出這個header,則只需要取變量$http_yd_token,則可以打印這個header了

log_format yuedu '$http_yd_token ...'

類似的如果要在log_format里打印 Xxx-Yyy這樣的消息頭,只需要使用$http_xxx_yyy即可

 

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM