简体   繁体   中英

Is this the right way of logging in Flask?

I have written a Flask App as follows:

import logging
from flask import Flask, jsonify
from mongo import Mongo
app = Flask(__name__)
app.config.from_object("config.ProductionConfig")


# routes to a particular change and patch number
@app.route("/<project>/")
def home(project):

    app.logger.info('testing info log')
    Mongo_obj = Mongo(ip=app.config["DB_HOST"], port=app.config["DB_PORT"],
                      username=app.config["DB_USERNAME"],

.....................
if __name__ == '__main__':
    app.run(host = '0.0.0.0', port = '5000')

Now, the problem I face is, when I look at the logs of the Flask application, all I see is the following:

* Serving Flask app "service" (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: off
 * Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
172.16.40.189 - - [01/Oct/2019 14:44:29] "GET /abc HTTP/1.1" 200 -
172.16.11.231 - - [01/Oct/2019 14:44:29] "GET /abc HTTP/1.1" 200 -
............

Is there something specific that needs to be done in order to see the log message? Do I need to run the Flask App in debug mode?

If not in debug mode the default log level is WARNING . That's why you don't see your logs. If you'd like your logs to contain INFO level ones you must set it within the logger, eg:

app = Flask(__name__)
app.logger.setLevel(logging.INFO)

This is how I set log levels in our app. I use the create_app function to create a flask app with error handling logging & other necessary configurations. Here is the snippet:

from flask import Flask
import logging


def create_app(test_config=None):
    # create and configure the app
    app = Flask(__name__)
    app.logger.setLevel(logging.ERROR)

    # Test Log levels
    app.logger.debug("debug log info")
    app.logger.info("Info log information")
    app.logger.warning("Warning log info")
    app.logger.error("Error log info")
    app.logger.critical("Critical log info")
    return app

app = create_app()

Output show only error and lower logs are visible for now

 * Restarting with stat
[2022-12-12 17:38:39,375] ERROR in __init__: Error log info
[2022-12-12 17:38:39,375] CRITICAL in __init__: Critical log info

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM