我似乎无法进行日志记录工作。以下不会向控制台打印任何内容。 我一直在深入研究官方文档、SO,甚至 Reddit...但似乎没有什么对我有用:/
from flask import Flask, request, jsonify
from logging.config import dictConfig
import urllib.request
import logging
import sys
import os
def create_app():
# https://betterstack.com/community/guides/logging/how-to-start-logging-with-flask/
dictConfig(
{
"version": 1,
"formatters": {
"default": {
"format": "[%(asctime)s] %(levelname)s in %(module)s: %(message)s",
}
},
"handlers": {
"console": {
"class": "logging.StreamHandler",
"stream": "ext://sys.stdout",
"formatter": "default",
}
},
"root": {"level": "DEBUG", "handlers": ["console"]},
}
)
app = Flask(__name__)
LOGGER = logging.getLogger("root")
@app.get('/whatever')
def view_zuerivelo_publibike() -> Flask.response_class:
LOGGER.info('HELLO!') // nothing gets logged here
# fetch raw XML
try:
response = urllib.request.urlopen(some_uri).read()
except Exception as e:
return jsonify({ 'message': e }), 500
LOGGER.info(response) // nothing gets logged here
return jsonify(response), 200
return app
if __name__ == '__main__':
create_app().run(debug=True, use_reloader=False)
虽然您已经配置了根记录器,但 Flask 默认情况下使用自己的记录器。您可以显式设置 app.logger 以使用自定义记录器或配置根记录器和flask.app 记录器。
"loggers": {
"flask.app": {"level": "DEBUG", "handlers": ["console"], "propagate": False},
}
然后设置
LOGGER = logging.getLogger("flask.app")
from flask import Flask, request, jsonify
from logging.config import dictConfig
import logging
def create_app():
dictConfig(
{
"version": 1,
"formatters": {
"default": {
"format": "[%(asctime)s] %(levelname)s in %(module)s: %(message)s",
}
},
"handlers": {
"console": {
"class": "logging.StreamHandler",
"stream": "ext://sys.stdout",
"formatter": "default",
}
},
"root": {"level": "DEBUG", "handlers": ["console"]},
"loggers": {
"flask.app": {
"level": "DEBUG",
"handlers": ["console"],
"propagate": False,
},
},
}
)
app = Flask(__name__)
LOGGER = logging.getLogger("flask.app")
@app.get("/whatever")
def view_zuerivelo_publibike():
LOGGER.info("HELLO!")
try:
some_uri = "http://example.com/data.xml"
response = "Hello, World!"
except Exception as e:
LOGGER.error(f"Error fetching URI: {e}")
return jsonify({"message": str(e)}), 500
LOGGER.info(response)
return jsonify(response), 200
return app
if __name__ == "__main__":
create_app().run(debug=True, use_reloader=False)