python - gunicorn 访问日志格式

标签 python json gunicorn fluentd

我计划在 kubernetes 上通过 gunicorn 运行 flask。为了获得正确的日志记录,我想以 json 格式输出我的所有日​​志。

目前我正在使用 minikube 和 https://github.com/inovex/kubernetes-logging 进行测试能够流畅地收集日志。

由于以下原因,我设法正确格式化了错误日志(回溯): JSON formatted logging with Flask and gunicorn

我仍在为访问日志格式而苦恼。 我指定了以下 gunicorn 访问日志格式:

access_log_format = '{"remote_ip":"%(h)s","request_id":"%({X-Request-Id}i)s","response_code":"%(s)s","request_method":"%(m)s","request_path":"%(U)s","request_querystring":"%(q)s","request_timetaken":"%(D)s","response_length":"%(B)s"}'

并且生成的日志是 json 格式的。但是消息部分(基于 access_log_format 的格式)现在包含转义双引号,并且不会被 fluentd/ELK 解析到它的各个字段中

{"tags": [], "timestamp": "2017-12-07T11:50:20.362559Z", "level": "INFO", "host": "ubuntu", "path": "/usr/local/lib/python2.7/dist-packages/gunicorn/glogging.py", "message": "{\"remote_ip\":\"127.0.0.1\",\"request_id\":\"-\",\"response_code\":\"200\",\"request_method\":\"GET\",\"request_path\":\"/v1/records\",\"request_querystring\":\"\",\"request_timetaken\":\"19040\",\"response_length\":\"20\"}", "logger": "gunicorn.access"}

谢谢 Jpw

最佳答案

最简单的解决方案是将外部单引号更改为双引号,将内部双引号更改为单引号,如下所述。

--access-logformat  "{'remote_ip':'%(h)s','request_id':'%({X-Request-Id}i)s','response_code':'%(s)s','request_method':'%(m)s','request_path':'%(U)s','request_querystring':'%(q)s','request_timetaken':'%(D)s','response_length':'%(B)s'}"

以下是示例日志

{'remote_ip':'127.0.0.1','request_id':'-','response_code':'404','request_method':'GET','request_path':'/test','request_querystring':'','request_timetaken':'6642','response_length':'233'}
{'remote_ip':'127.0.0.1','request_id':'-','response_code':'200','request_method':'GET','request_path':'/','request_querystring':'','request_timetaken':'881','response_length':'20'}

关于python - gunicorn 访问日志格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47694878/

相关文章:

python - Gunicorn 工作人员在长时间的 API 调用后自行重启

django - Gunicorn Socket 文件丢失

python - 运行 scrapy 爬虫的最简单方法,这样它就不会阻止脚本

python - 尝试子类化 Mechanize 浏览器并创建登录方法

python - 如何成为一个伟大的python开源程序员?

java/jackson - 不要序列化包装类

django+nginx+gunicorn - 子域的喜悦

python - 对 numpy 数组的操作包含不同大小的行

ios - 如何使用 URL 参数和 UITableview 执行干净的 JSON 解码

mysql json数据类型在数组内搜索值