用 gunicorn 登录烧瓶

Logging in flask with gunicorn

我是一名从 Java 过渡到 Python 的开发人员。

我有一个部署在 gunicorn 上的烧瓶应用程序。为了调试应用程序,我使用了如下记录器

#For logging
from logging.handlers import RotatingFileHandler
import logging
from logging import Formatter


logger = logging.getLogger('backend-logging')
file_handler = RotatingFileHandler('test.log', maxBytes=10000, backupCount=1)
handler = logging.StreamHandler()
file_handler.setFormatter(Formatter(
    '%(asctime)s %(levelname)s: %(message)s '
    '[in %(pathname)s:%(lineno)d]'
))
handler.setFormatter(Formatter(
    '%(asctime)s %(levelname)s: %(message)s '
    '[in %(pathname)s:%(lineno)d]'
))
logger.addHandler(file_handler)
logger.addHandler(handler)
logger.setLevel(logging.INFO)
#EOL

在每个文件中,上面的代码片段用于记录错误、调试、信息消息。

logger.info('creating user with the data %s',json.dumps(data))

这是我的 wsgi 应用程序

from server import app

if __name__ == "__main__":
    app.run(debug=True)

当我使用以下命令启动我的应用程序时,它没有打印记录器。

gunicorn3 --bind 0.0.0.0:5000 --log-level DEBUG wsgi:app

如果这是记录应用程序日志的正确方法,有人可以帮助我吗?

您必须将 --access-logfile--error-logfile 指定为 '-',而 运行 您的 Gunicorn。这告诉 gunicorn 将错误和访问日志发送到 stdout 流。

示例

# make sure to give --access-logfile and --error-logfile as '-' to make gunicorn send logs to stdout
gunicorn app:app -b 0.0.0.0:5000 --workers 2 -k gevent --timeout 300 --worker-connections 1000 --max-requests 1000000 --limit-request-line 8190 --access-logfile '-' --error-logfile '-'

也许这会有所帮助。它使用 python 的 dictConfig 来设置日志记录。

Setting up logging for Gunicorn in a Flask application using Python's dictConfig