我正在尝试做一些与这里解释的非常相似的事情:https://sebest.github.io/post/protips-using-gunicorn-inside-a-docker-image/
我想让我的 Flask 应用程序 + gunicorn 都输出 JSON 格式的日志记录。我已经在 Flask 应用程序中使用它,但我似乎无法在 gunicorn 中使用它。
这是我当前的输出:
* Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
* Restarting with stat
* Debugger is active!
* Debugger pin code: 317-187-130
192.168.99.1 - - [12/Jan/2016 20:09:29] "GET /nothing HTTP/1.1" 404 -
{"asctime": "2016-01-12 20:20:25,541", "levelname": "WARNING", "module": "app", "funcName": "err", "lineno": 17, "message": "will assert false..."}
192.168.99.1 - - [12/Jan/2016 20:20:25] "GET /err HTTP/1.1" 500 -
{"asctime":
开头的行是代码 app.logger.warning('will assert false...')
的输出正确记录为 JSON。耶。以 192.168.99.1
开头的行是我的 gunicorn WSGI 服务器的输出,令人沮丧的是,它们不是 JSON 格式的。
这是我用来启动 gunicorn 的命令:
gunicorn --log-config gunicorn_logging.conf -c gunicorn_config.py api.app:app
gunicorn_logging.conf
文件包含:
[loggers]
keys=root, gunicorn.error
[handlers]
keys=console
[formatters]
keys=json
[logger_root]
level=INFO
handlers=console
[logger_gunicorn.error]
level=ERROR
handlers=console
propagate=0
qualname=gunicorn.error
[handler_console]
class=StreamHandler
formatter=json
args=(sys.stdout, )
[formatter_json]
class=jsonlogging.JSONFormatter
文件 gunicorn_config.py
包含:
import os
import multiprocessing
addr = os.environ.get('HTTP_ADDR', '0.0.0.0')
port = os.environ.get('HTTP_PORT', '5000')
loglevel = os.environ.get('LOG_LEVEL', 'info')
bind = '{0}:{1}'.format(addr, port)
workers = multiprocessing.cpu_count() * 5 + 1
worker_class = 'gevent'
timeout = 0
这是 pip freeze
的输出:
aniso8601==1.1.0
coverage==4.0.3
flake8==2.5.1
Flask==0.10.1
Flask-MySQLdb==0.2.0
Flask-RESTful==0.3.5
Flask-Script==2.0.5
gevent==1.1rc3
greenlet==0.4.9
gunicorn==19.4.5
itsdangerous==0.24
Jinja2==2.8
json-logging-py==0.2
MarkupSafe==0.23
marshmallow==2.4.2
mccabe==0.3.1
mysqlclient==1.3.7
nose==1.3.7
pep8==1.5.7
pyflakes==1.0.0
python-dateutil==2.4.2
python-json-logger==0.1.4
pytz==2015.7
six==1.10.0
SQLAlchemy==1.0.11
Werkzeug==0.11.3
最佳答案
要获取访问日志以及您的配置文件应该如下所示:
[loggers]
keys=root, gunicorn.error, gunicorn.access
...
[logger_gunicorn.access]
level=(DEBUG|INFO|ERROR)
handlers=console
propagate=0
qualname=gunicorn.access
访问记录在 INFO 日志级别,因此如果您想显示它们,请确保将“logger_gunicorn.access”标签中的日志级别至少设置为 INFO
关于python - 使用 Flask 和 gunicorn 进行 JSON 格式的日志记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34753214/