How to add stdout and stderr to logger file in fla

2020-06-08 13:01发布

问题:

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?

回答1:

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.



标签: python flask