nginx自定义访问日志

0.需求

(1)特定url请求打印json日志到特定的日志文件

(2)日志中打印request中的自定义header字段

(3)日志中打印response中的自定义header字段

1.实现

具体化一下需求,将/api/test/index/前缀路径的请求日志打印到access-index.log文件,request header添加client-id,response header添加x-server-id,并在nginx日志打印出这两个自定义header。其他路径的请求日志打印到默认的access.log文件。

通过自定义http模块下的log_format来打印,nginx.conf配置如下(nginx版本1.12.2):

http {
    include       /opt/nginx/mime.types;
    default_type  application/octet-stream;

    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                        '$status $body_bytes_sent "$http_referer" '
                        '$upstream_response_time $request_time '
                        '$upstream_response_time $request_time '
                        '"$http_user_agent" "$http_x_forwarded_for" ';
   
    log_format  json  '{"time_local":"$time_local",'
                          '"remote_addr":"$remote_addr",'
                          '"remote_user":"$remote_user",'
                          '"server_addr":"$server_addr",'
                          '"upstream_addr":"$upstream_addr",'
                          '"request_method":"$request_method",'
                          '"request_uri":"$request_uri",'
                          '"server_protocol":"$server_protocol",'
                          '"status":$status,'
                          '"body_bytes_sent":"$body_bytes_sent",'
                          '"http_referer":"$http_referer",'
                          '"upstream_response_time":"$upstream_response_time",'
                          '"request_time":"$request_time",'
                          '"http_user_agent":"$http_user_agent",'
                          '"http_x_forwarded_for":"$http_x_forwarded_for",'
                          '"client_id":"$http_client_id",' 
                          '"server_id":"$upstream_http_x_server_id"'
                      '}'; 

    access_log  /opt/nginx/logs/access.log  main;

    sendfile        on;
    #tcp_nopush     on;

    keepalive_timeout  65;

    #gzip  on;

    include default.conf;
}

default.conf配置如下

upstream webtest{
    server  ip:port;
}


server {
    listen  80;
    server_name ip;
    charset utf-8;

    location ~ /api/test/index/{
        proxy_pass http://webtest;
        client_max_body_size    1024m;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
        access_log  /opt/nginx/logs/access-index.log  json;
    }

    location ~ /api/test/{
        proxy_pass http://tracker;
        client_max_body_size    1024m;
        proxy_set_header Host $host;
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    }

    
}
原文地址:https://www.cnblogs.com/ouym/p/15393191.html