Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make Flask log to stdout instead of stderr?

Flask does all kinds of logging automatically, for example when receiving a POST request Flask will automatically log it:

127.0.0.1 - - [05/Jul/2019 18:18:16] "POST /test/ HTTP/1.1" 200 -

The problem is that this logging is done to stderr, I would like it to instead do all the same logging, with the default formatting, but log to sys.stdout instead.

I've tried something like this:

import logging
import sys

app = flask.Flask(__name__)
handler = logging.StreamHandler(sys.stdout)
app.logger.addHandler(handler)

And based on Flask's documentation I tried:

import sys
from logging.config import dictConfig

dictConfig({
    'version': 1,
    'formatters': {'default': {
        'format': '[%(asctime)s] %(levelname)s in %(module)s: %(message)s',
    }},
    'handlers': {'wsgi': {
        'class': 'logging.StreamHandler',
        'stream': 'sys.stdout',
        'formatter': 'default'
    }},
    'root': {
        'level': 'INFO',
        'handlers': ['wsgi']
    }
})

app = flask.Flask(__name__)

But the first one doesn't have the desired effect and the second one just crashes.

like image 577
ruohola Avatar asked Oct 21 '25 23:10

ruohola


1 Answers

Based on @RomanPerekhrest's comment, this did the job:

import sys
from logging.config import dictConfig

dictConfig({
    'version': 1,
    'formatters': {'default': {
        'format': '[%(asctime)s] %(levelname)s in %(module)s: %(message)s',
    }},
    'handlers': {'wsgi': {
        'class': 'logging.StreamHandler',
        'stream': 'ext://sys.stdout',  # <-- Solution
        'formatter': 'default'
    }},
    'root': {
        'level': 'INFO',
        'handlers': ['wsgi']
    }
})


app = flask.Flask(__name__)
like image 97
ruohola Avatar answered Oct 23 '25 13:10

ruohola



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!