将stdout记录到gunicorn访问日志?

edA*_*a-y 8 flask gunicorn

当我将我的Flask应用程序用gunicorn写入stdout时,似乎不再去任何地方(简单的print语句不会出现).有没有办法将stdout捕获到gunicorn访问日志中,或者获取访问日志的句柄并直接写入它?

Joh*_*Mee 12

使用日志记录:将流设置为stdout

import logging

app.logger.addHandler(logging.StreamHandler(sys.stdout))
app.logger.setLevel(logging.DEBUG)

app.logger.debug("Hello World")
Run Code Online (Sandbox Code Playgroud)


Xua*_*uan 6

这个问题有两个解决方案。它们可能比其他的更长,但最终它们探讨了 Python 底层如何完成日志记录。

1.在Flask应用程序中设置日志配置

有关日志记录的官方 Flask 文档适用于gunicorn。https://flask.palletsprojects.com/en/1.1.x/logging/#basic-configuration

  • 一些可以尝试的示例代码:
from logging.config import dictConfig

from flask import Flask

dictConfig(
    {
        "version": 1,
        "disable_existing_loggers": False,
        "formatters": {
            "default": {
                "format": "[%(asctime)s] [%(process)d] [%(levelname)s] in %(module)s: %(message)s",
                "datefmt": "%Y-%m-%d %H:%M:%S %z"
            }
        },
        "handlers": {
            "wsgi": {
                "class": "logging.StreamHandler",
                "stream": "ext://flask.logging.wsgi_errors_stream",
                "formatter": "default",
            }
        },
        "root": {"level": "DEBUG", "handlers": ["wsgi"]},
    }
)
app = Flask(__name__)

@app.route("/")
def hello():
    app.logger.debug("this is a DEBUG message")
    app.logger.info("this is an INFO message")
    app.logger.warning("this is a WARNING message")
    app.logger.error("this is an ERROR message")
    app.logger.critical("this is a CRITICAL message")
    return "hello world"
Run Code Online (Sandbox Code Playgroud)
  • 运行与gunicorn
gunicorn -w 2 -b 127.0.0.1:5000 --access-logfile - app:app
Run Code Online (Sandbox Code Playgroud)
  • 使用curl请求它
curl http://127.0.0.1:5000
Run Code Online (Sandbox Code Playgroud)
  • 这将生成以下日志
[2020-09-04 11:24:43 +0200] [2724300] [INFO] Starting gunicorn 20.0.4
[2020-09-04 11:24:43 +0200] [2724300] [INFO] Listening at: http://127.0.0.1:5000 (2724300)
[2020-09-04 11:24:43 +0200] [2724300] [INFO] Using worker: sync
[2020-09-04 11:24:43 +0200] [2724311] [INFO] Booting worker with pid: 2724311
[2020-09-04 11:24:43 +0200] [2724322] [INFO] Booting worker with pid: 2724322
[2020-09-04 11:24:45 +0200] [2724322] [DEBUG] in flog: this is a DEBUG message
[2020-09-04 11:24:45 +0200] [2724322] [INFO] in flog: this is an INFO message
[2020-09-04 11:24:45 +0200] [2724322] [WARNING] in flog: this is a WARNING message
[2020-09-04 11:24:45 +0200] [2724322] [ERROR] in flog: this is an ERROR message
[2020-09-04 11:24:45 +0200] [2724322] [CRITICAL] in flog: this is a CRITICAL message
127.0.0.1 - - [04/Sep/2020:11:24:45 +0200] "GET / HTTP/1.1" 200 11 "-" "curl/7.68.0"
Run Code Online (Sandbox Code Playgroud)

2.在Gunicorn中设置日志配置

  • 与上面相同的应用程序代码,但没有该dictConfig({...})部分

  • 创建一个logging.ini文件

[loggers]
keys=root

[handlers]
keys=consoleHandler

[formatters]
keys=simpleFormatter

[logger_root]
level=DEBUG
handlers=consoleHandler

[handler_consoleHandler]
class=StreamHandler
level=DEBUG
formatter=simpleFormatter
args=(sys.stdout,)

[formatter_simpleFormatter]
format=[%(asctime)s] [%(process)d] [%(levelname)s] - %(module)s - %(message)s
datefmt=%Y-%m-%d %H:%M:%S %z
Run Code Online (Sandbox Code Playgroud)
  • 运行带有--log-config logging.ini选项的gunicorn,即gunicorn -w 2 -b 127.0.0.1:5000 --access-logfile - --log-config logging.ini app:app