简体   繁体   中英

How to add stdout and stderr to logger file in 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?

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, eg:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM