为什么Flask会将日志写入我的日志?

2024-05-16 23:30:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在创建一个简单的应用程序,在flask中以调试模式运行。 我决定用日志来写日志

    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')

但我发现in-app.log(我的应用程序不是“app.py”)Flask除了写我的日志之外还写自己的日志。 比如:

[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 -

为什么会发生这种情况?我如何将烧瓶日志记录与自己的日志记录分开


Tags: importlogapp应用程序localhosthttpflaskmain
1条回答
网友
1楼 · 发布于 2024-05-16 23:30:47

这是因为logging.basicConfig配置了根记录器。所有创建的记录器propagate log messages to their parents,除非明确告知他们不要:

app.logger.propagate = False

禁用记录器也是一个选项:

app.logger.disabled = True

或者设置不太详细的模式

app.logger.setLevel(logging.WARNING)

仅将flask日志保存到另一个文件更为复杂。您必须删除StreamHandler并手动创建FileHandlerFormatterlogging模块为您提供了很大的灵活性,但也可以是:

# 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

相关问题 更多 >