nginx访问日志作为JSON与查询string键值对

我想制作一个自定义的nginx访问日志,不仅是JSON,而且还有查询中每个键=值的JSON键值对。

为Nginx制作JSON日志很简单:

log_format main '{' '"remote_addr": "$remote_addr",' '"remote_user": "$remote_user",' '"time_local": "$time_local",' '"request": "$request",' '"status": "$status",' '"body_bytes_sent": "$body_bytes_sent",' '"http_referer": "$http_referer",' '"http_user_agent": "$http_user_agent"' '}'; 

但是可以说请求是GET /blah?foo=bar&hi=there%20mom

我在json中寻找2个额外的东西

... 'http_user_agent':'chrome', 'foo':'bar', 'hi':'there mom' }

可以这样做吗? 如果是这样,我怎么能确保生成的JSON是有效的? (解码URL转义等)。

请看看HttpSetMiscModule ( GitHub Repo )。 你将不得不自己编译nginx来包含这个模块。

之后你可以做这样的事情:

 GET /blah?foo=bar&hi=there%20mom set $foo $arg_foo; set $hi $arg_hi; set_quote_json_str $foo; set_quote_json_str $hi; log_format main '{' '"remote_addr": "$remote_addr",' '"remote_user": "$remote_user",' '"time_local": "$time_local",' '"request": "$request",' '"status": "$status",' '"body_bytes_sent": "$body_bytes_sent",' '"http_referer": "$http_referer",' '"http_user_agent": "$http_user_agent"' '"arg_foo": "$foo"' '"arg_hi": "$hi"' '}'; 

请注意,我没有testing过这个!