pythonflask

How to log/display app name, host and port upon startup


In my simple Flask app, I've created the following .flaskenv file:

FLASK_APP=simpleflask.app
FLASK_RUN_HOST=127.0.0.1
FLASK_RUN_PORT=60210

Now, I would like my app to log the following message upon startup:

Running my.flask.app on http://127.0.0.1:60210 ...

The message should be logged just once, not per each request.

Preferably, I would like to avoid parsing .flaskenv on my own, but rather use some internal Flask objects and obtain this information dynamically.

Any idea how to achieve this?


Solution

  • app = Flask(__name__)
    # ...
    with app.app_context():
        app.logger.info(f"Running {os.environ.get('FLASK_APP')} on http://{os.environ.get('FLASK_RUN_HOST')}:{os.environ.get('FLASK_RUN_PORT')} ...")