Generally speaking, logging from Flask is straightforward. Flask uses standard Python logging, and you access the logger object via app.logger. So a call to the logger might look like
app.logger.info(f"{user.username} logged in")
If you are using Flask blueprints, it gets slightly more complicated because you don't have the app object directly available. However, Flask knows you probably will need it, so they give you a way to get it, by importing current_app
from flask import current_app
And you can just use current_app in the blueprint where you would otherwise have used app
current_app.logger.info(f"(user.username} logged in")
However, suppose you start a thread that will continue to do something after the request that started it has completed, and you want to log from that thread. You will probably discover that this doesn't work, and you get a runtime error like
RuntimeError: Working outside of application context.
because the application context disappeared when the request returned. However, the logger is still there, and references to the logger will still work, so all you need to do is store app.logger (or current_app.logger) somewhere, or pass it into the thread, and logging should be available. I've just been including the logger as an argument to whatever function I'm starting in the thread. Here's what it looks like from a blueprint
executor = concurrent.futures.ThreadPoolExecutor(1)
def longRunningTestFunction(logger):
logger.info("going to sleep")
time.sleep(3600)
logger.info("waking up")
@test_blueprint.route('/test')
def run_threadtest():
current_app.logger.info("starting thread")
executor.submit(longRunningTestFunction,current_app.logger)
return "test thread submitted"
Without doing any additional setup, this works fine from Cloud Run, where Docker passes the logger messages to stdout/stderr, and Cloud Run logs it from there. Of course you can do the normal Python logging customizations as desired.