简体   繁体   中英

Why Flask writes logs into my logging log?

I in proccess of creating simple app which i run in debug mode in flask. I decided to use logging to write logs.

    import logging
    dlog = logging
    dlog.basicConfig(filename='app.log', format='%(asctime)s %(message)s',
                     datefmt='[%Y-%m-%d | %H:%M:%S]', level=logging.INFO)
    ...
if __name__ == '__main__':
    app.run(debug=True, host='localhost', port='8002')

But I've discovered that in app.log(and my app is is not called "app.py") Flask writes own logs in addition to mine. like:

[2020-05-01 | 21:36:04]  * Running on http://localhost:8002/ (Press CTRL+C to quit)
[2020-05-01 | 21:36:04]  * Restarting with stat
[2020-05-01 | 21:36:05]  * Debugger is active!
[2020-05-01 | 21:36:05]  * Debugger PIN: 290-968-029
[2020-05-01 | 21:36:15] 127.0.0.1 - - [01/May/2020 21:36:15] "[37mGET / HTTP/1.1[0m" 200 -
[2020-05-01 | 21:36:15] 127.0.0.1 - - [01/May/2020 21:36:15] "[36mGET /static/js/main.js HTTP/1.1[0m" 304 -

Why does this happening and how can I separate flask logging from my own?

That's because logging.basicConfig configures the root logger. All created loggers propagate log messages to their parents unless they are explicitly told not to:

app.logger.propagate = False

Disabling the logger is also an option:

app.logger.disabled = True

or setting less verbose mode

app.logger.setLevel(logging.WARNING)

Making flask log only to another file is more complicated. You have to remove StreamHandler and create FileHandler and Formatter manually. logging module gives you a lot of flexibility, but can be cumberstone:

# https://docs.python.org/3/library/logging.html#logrecord-attributes
formatter = logging.Formatter("{asctime:s} {name} [{levelname}] {filename}:{lineno} {msg}", style="{")
file_handler = logging.FileHandler("flask.log")
file_handler.setFormatter(formatter)
# set log level threshold for this handler
file_handler.setLevel(logging.INFO)
# flask creates StreamHandler for you, if you don't want that
# just set handlers to empty list
app.logger.handlers = []
app.logger.addHandler(file_handler)
# set log level on the flask logger
app.logger.setLevel(logging.INFO)
# don't propagate to parent logger (logging.root) to not duplicate
# the logs if you're handling log messages in root logger
app.logger.propagate = False

app.logger.info("spanish iniquisition")

# flask.log:
# 2020-05-02 09:12:31,631 t [INFO] t.py:16 spanish iniquisition

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