How to log from Flask to both the console and deployment logs?

Question:
Why isn’t app.logger.info("Info log message") appearing in my console log even after app.logger.addHandler(logging.StreamHandler()), nor in my deployment logs?

Both the console and the deployment logs show all the usual server logs and other messages from Flask, but not my “Info log message”. Printing to stdout or stderr appears on the console, but not in the deployment logs. Warnings from pysox appear in the deployment logs as shown below, but not in the console.

output_file: audio.wav already exists and will be overwritten on build

Please help!

Repl link: https://replit.com/@jsalsman/webrec#main.py

import logging

app = Flask(__name__)
app.logger.addHandler(logging.StreamHandler())
app.logger.info("Info log message 1")

@app.route('/record') 
def record():
  app.logger.info("Info log message 2")
1 Like

You have to configure the logging:

logging.basicConfig(level=logging.DEBUG,
                    format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
3 Likes

Thank you, Sky!

I am marking this as the best solution for Replit at this time:

from sys import stderr
log = lambda message: stderr.write(message + '\n')

While Sky’s approach worked for the deployment logs, :relieved: it changed the default format even if I didn’t include the format or used format='%(message)s', and it still wouldn’t show in the console even with app.logger.addHandler(logging.StreamHandler()), which in turn caused duplicates in the deployment logs.

But now, sys.stderr.write('...\n') works for both, so thanks also to the Replit devs, presumably.

[Replit Solution moved to top to show at the top of the thread.]

3 Likes

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.