前言
假设在请求中自定义了一个请求头,key为"version
",参数值为“1.2.3
”,需要在日志中捕获这个请求头。
nginx日志配置
只需要用变量http_version
就能捕获到自定义的version
请求头。示例:
log_format main '{"@timestamp": "$time_iso8601", ' '"connection": "$connection", ' '"version": "$http_version", ' '"remote_addr": "$remote_addr", ' '"remote_user": "$remote_user", ' '"request_method": "$request_method", ' '"request_uri": "$request_uri", ' '"request_length": "$request_length", ' '"server_protocol": "$server_protocol", ' '"status": "$status", ' '"body_bytes_sent": "$body_bytes_sent", ' '"http_referer": "$http_referer", ' '"http_user_agent": "$http_user_agent", ' '"http_x_forwarded_for": "$http_x_forwarded_for", ' '"upstream_addr": "$upstream_addr", ' '"request_time": "$request_time"}';
测试
- 使用curl请求,指定请求头
curl -I -s http://127.0.0.1 -H 'version:123456' -o /dev/null
- 观察nginx请求日志是否记录到version值
{"@timestamp": "2023-04-12T15:14:13+00:00", "connection": "12", "version": "123456", "remote_addr": "172.1.7.1", "remote_user": "-", "request_method": "HEAD", "request_uri": "/", "request_length": "90", "server_protocol": "HTTP/1.1", "status": "200", "body_bytes_sent": "0", "http_referer": "-", "http_user_agent": "curl/7.74.0", "http_x_forwarded_for": "-", "upstream_addr": "-", "request_time": "0.000"}