spice and wolfspice and wolf Be the One you wanna Be

nginx调试

日志自定义

你可以在日志中自定义一些输出变量,以方便在出错时更详细的了解错误信息。

http {
    log_format geoproxy
               '[$time_local] $remote_addr '
               '$realip_remote_addr $remote_user '
               '$proxy_protocol_server_addr $proxy_protocol_server_port '
               '$request_method $server_protocol '
               '$scheme $server_name $url $status '
               '$request_time $body_bytes_sent '
               '$geoip_city_country_code3 $geoip_region '
               '"$geoip_city" $http_x_forwarded_for '
               '$upstream_status $upstream_response_time '
               '"$http_referer" "$http_user_agent"';
     # ...
}

log_format配置中将很多nginx的内置参数配置到日志中,参数就不一一例举了。而日志配置的使用则需要借助于access_log指令:

server {
    access_log /var/log/nginx/access.log geoproxy;
    # ...
}

配置错误日志

error_log /var/log/nginx/error.log warn;

这条指令允许在除了if以外的所有上下文中配置,第一个参数为写入错误日志的目录,第二个参数为错误日志等级,默认为error。

请求追溯

当你需要将部署的应用的日志和nginx日志关联起来以便于理解端到端请求过程时,下面的指令将对你有所帮助。

log_format trace '$remote_addr - $remote_user [$time_local] '
                 '"$request" $status $body_bytes_cent '
                 '"$http_referer" "$http_user_agent" '
                 '"$http_x_forwarded_for" $request_id';
upstream backend {
    server 10.0.0.42;
}
server {
    listen 80;
    # Add the header X-Request-ID to the response to the client
    add_header X-Request-ID $request_id;
    location / {
        proxy_pass http://backend;
        # Send the header X-Request_ID to the appliction
        proxy_set_header X-Request-ID $request_id;
        access_log /var/log/nginx/access_trace.log trace;
    }
}

在上面配置中我们通过$request_id变量将nginx-上游服务-客户端串联起来,通过这个变量我们可以跟踪请求在三者中的如何运作的。我们可以看到在log_format trace中配置了$request_id变量,所以这个变量将记录在nginx的access_log日志中;同样我们通过proxy_set_header指令,在代理请求中加入了值为$request_id的X-Request-ID请求头,并通过add_header指令将X-Request-ID加到了响应头信息中。

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

Press ESC to close