Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add stdout and stderr to logger file in flask

Tags:

python

flask

I want to log the stdout & stderr to log files, and this is what I tried.

app = Flask(__name__)
app.logger.setLevel(logging.INFO)  # use the native logger of flask
app.logger.disabled = False
handler = logging.handlers.RotatingFileHandler(
    SYSTEM_LOG_FILENAME,
    'a',
    maxBytes=1024 * 1024 * 100,
    backupCount=20
    )

formatter = logging.Formatter(\
    "%(asctime)s - %(levelname)s - %(name)s: \t%(message)s")
handler.setFormatter(formatter)
app.logger.addHandler(handler)

@app.route('/')
def hello():

    return 'Hello World'
if __name__ == '__main__':
    app.run()        

Then I would like to log the console output in files. such as

* Running on http://127.0.0.1:5000/
127.0.0.1 - - [24/May/2013 14:55:14] "GET / HTTP/1.1" 200 -
127.0.0.1 - - [24/May/2013 14:55:14] "GET /favicon.ico HTTP/1.1" 404 -

what can I do?

like image 209
Kimmi Avatar asked May 24 '13 18:05

Kimmi


People also ask

How do you set up a Flask logger?

To start with logging in Flask, first import the logging module from Python. This logger module comes out of the box from the Python installation and does not need configuration. The Python logging module logs events based on pre-defined levels. The recorded log events are known as log records.

How do you write log to stdout?

There is a parameter for you CustomLog sets log filename and format. If you configure /proc/self/fd/1 as the log filename, Apache2 process will now write to its own stdout.

How do I add screen logging to my Flask application?

We first initialize a Flask application class and define the static and template folders. Then we define a route ('/') and tell the application that it should render index. html. The last line tells the application to expose itself on port 5000.


1 Answers

The logging messages you mention don't come from flask's logger, the come from werkzeug's logger, that means you also need to add your handler to that logger instance to make it work, e.g:

log = logging.getLogger('werkzeug')
log.setLevel(logging.INFO)
log.addHandler(handler)

If you look at how werkzeug initializes its logger, you'll see that it adds a default handler only if logging wasn't already set up. That means if you set it up before wekzeug does, it won't use the default StreamHandler but the handler you supply.

like image 170
mata Avatar answered Oct 25 '22 08:10

mata