I'm trying to get my Flask app to print its logs onto a file named "backend.log". I tested it on a dummy Flask app, with the following script:
import logging
from flask import Flask
app = Flask(__name__)
logging.basicConfig(filename="backend.log", level=logging.DEBUG, format="%(asctime)s:%(levelname)s:%(message)s")
@app.route("/")
def home():
return "<h1>Hello World!</h1>"
if __name__ == "__main__":
app.run(debug=True)
This worked fine, and printed the following onto "backend.log".
2022-08-17 02:01:59,793:INFO: * Running on http://127.0.0.1:5000 (Press CTRL C to quit)
2022-08-17 02:01:59,796:INFO: * Restarting with stat
2022-08-17 02:02:00,114:WARNING: * Debugger is active!
2022-08-17 02:02:00,123:INFO: * Debugger PIN: 117-718-608
However, when I tried on a different repo/folder with my actual Flask app that I'm working on, it doesn't work anymore. The logging keeps printing to the console.
import logging
from flask import Flask
from endpoints.database_endpoints import database
from endpoints.model_endpoints import model
from endpoints.workspace_endpoints import workspace
# Flask setup
app = Flask(__name__)
app.register_blueprint(database, url_prefix="")
app.register_blueprint(model, url_prefix="")
app.register_blueprint(workspace, url_prefix="")
# Logging setup
logging.basicConfig(filename="backend.log", level=logging.DEBUG, format="%(asctime)s:%(levelname)s:%(message)s")
@app.route("/")
def home():
return "<h1>Endpoint is up and running</h1>"
if __name__ == "__main__":
app.run(debug=True)
Console result:
* Serving Flask app 'index' (lazy loading)
* Environment: development
* Debug mode: on
2022-08-17 02:08:30,111:INFO - * Running on http://127.0.0.1:5000 (Press CTRL C to quit)
2022-08-17 02:08:30,113:INFO - * Restarting with stat
2022-08-17 02:08:30,708:WARNING - * Debugger is active!
2022-08-17 02:08:30,716:INFO - * Debugger PIN: 117-718-608
There also wasn't a "backend.log" file created, either, unlike before. What am I missing here?
CodePudding user response:
Ok so I tested a couple of things, and apparently it was because the blueprint imports messed with the logging. See this post: How do I log a Python error with debug information?
Solution:
# Logging setup must be done before imports
import logging
logging.basicConfig(filename="backend.log", level=logging.DEBUG, format="%(asctime)s:%(levelname)s:%(message)s")
from flask import Flask
from endpoints.database_endpoints import database
from endpoints.model_endpoints import model
from endpoints.workspace_endpoints import workspace
# Flask setup
app = Flask(__name__)
app.register_blueprint(database, url_prefix="")
app.register_blueprint(model, url_prefix="")
app.register_blueprint(workspace, url_prefix="")
@app.route("/")
def home():
return "<h1>Endpoint is up and running</h1>"
if __name__ == "__main__":
app.run(debug=True)