如何从nginx生成JSON日志? [英] How to generate a JSON log from nginx?
问题描述
我正在尝试从nginx生成JSON日志.
I'm trying to generate a JSON log from nginx.
我知道类似这,但是我要记录的某些字段包括用户生成的输入(例如HTTP标头),需要正确进行转义.
I'm aware of solutions like this one but some of the fields I want to log include user generated input (like HTTP headers) which need to be escaped properly.
我知道2011年10月至2008年5月的Nginx变更日志条目说:
I'm aware of the nginx changelog entries from Oct 2011 and May 2008 that say:
*) Change: now the 0x7F-0x1F characters are escaped as \xXX in an
access_log.
*) Change: now the 0x00-0x1F, '"' and '\' characters are escaped as \xXX
in an access_log.
,但这仍然无济于事,因为\xXX
在JSON字符串中无效".
but this still doesn't help since \xXX
is invalid in a JSON string.
我还查看了具有set_quote_json_str
指令的HttpSetMiscModule 模块,但这仅仅是似乎在没有帮助的字符串周围添加\x22
.
I've also looked at the HttpSetMiscModule module which has a set_quote_json_str
directive, but this just seems to add \x22
around the strings which doesn't help.
是否有其他解决方案可以从nginx以JSON格式登录的想法?
Any idea for other solutions to log in JSON format from nginx?
推荐答案
最后,看来我们可以使用没有任何模块的纯正nginx做到这一点.只需定义:
Finally it looks like we have good way to do this with vanilla nginx without any modules. Just define:
log_format json_combined escape=json
'{'
'"time_local":"$time_local",'
'"remote_addr":"$remote_addr",'
'"remote_user":"$remote_user",'
'"request":"$request",'
'"status": "$status",'
'"body_bytes_sent":"$body_bytes_sent",'
'"request_time":"$request_time",'
'"http_referrer":"$http_referer",'
'"http_user_agent":"$http_user_agent"'
'}';
请注意,在Nginx 1.11.8中添加了 escape = json . http://nginx.org/en/docs/http/ngx_http_log_module.html#log_format
Note that escape=json was added in nginx 1.11.8. http://nginx.org/en/docs/http/ngx_http_log_module.html#log_format
这篇关于如何从nginx生成JSON日志?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!