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?
Answer
You can use os.environ.get('<VAR_NAME>')
to get values of envvars imported by flask run
command from .flaskenv
file at runtime.
You can print info you want with the following block before the app.run
is executed:
flaskApp = os.environ.get('FLASK_APP')
flaskRunHost = os.environ.get('FLASK_RUN_HOST')
flaskRunPort = os.environ.get('FLASK_RUN_PORT')
print(f"Running {flaskApp} on http://{flaskRunHost}:{flaskRunPort} ...")
(replace print
with preferred logging method)
Enjoyed this article?
Check out more content on our blog or follow us on social media.
Browse more articles