小编典典

flask日志记录-无法将其写入文件

flask

好的,这是我设置所有内容的代码:

if __name__ == '__main__':
    app.debug = False

    applogger = app.logger

    file_handler = FileHandler("error.log")
    file_handler.setLevel(logging.DEBUG)

    applogger.setLevel(logging.DEBUG)
    applogger.addHandler(file_handler)

    app.run(host='0.0.0.0')

发生的是

  1. error.log被创建
  2. 没有写任何东西
  3. 尽管未添加StreamHandler并将debug设置为false,但我仍然将所有内容都添加到STDOUT中(这可能是正确的,但仍然看起来很奇怪)
    我是完全离开这里还是发生了什么事?

阅读 1222

收藏
2020-04-06

共1个答案

小编典典

为什么不这样做呢?

if __name__ == '__main__':
    init_db()  # or whatever you need to do

    import logging
    logging.basicConfig(filename='error.log',level=logging.DEBUG)

    app.run(host="0.0.0.0")

如果现在启动应用程序,你将看到error.log包含:

INFO:werkzeug: * Running on http://0.0.0.0:5000/

有关更多信息,请访问http://docs.python.org/2/howto/logging.html

好的,因为你坚持使用我展示的方法不能拥有两个处理程序,所以我将添加一个示例,使这一点很清楚。首先,将此日志代码添加到你的主目录中:

import logging, logging.config, yaml
logging.config.dictConfig(yaml.load(open('logging.conf')))

现在还添加一些调试代码,以便我们可以看到我们的设置可以正常工作:

logfile    = logging.getLogger('file')
logconsole = logging.getLogger('console')
logfile.debug("Debug FILE")
logconsole.debug("Debug CONSOLE")

剩下的就是“ logging.conf”程序。让我们使用它:

version: 1
formatters:
  hiformat:
    format: 'HI %(asctime)s - %(name)s - %(levelname)s - %(message)s'
  simple:
    format: '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
handlers:
  console:
    class: logging.StreamHandler
    level: DEBUG
    formatter: hiformat
    stream: ext://sys.stdout
  file:
    class: logging.FileHandler
    level: DEBUG
    formatter: simple
    filename: errors.log
loggers:
  console:
    level: DEBUG
    handlers: [console]
    propagate: no
  file:
    level: DEBUG
    handlers: [file]
    propagate: no
root:
  level: DEBUG
  handlers: [console,file]

此配置比所需的配置复杂得多,但它还显示了日志记录模块的某些功能。

现在,当我们运行我们的应用程序时,我们看到以下输出(werkzeug和console-logger):

HI 2013-07-22 16:36:13,475 - console - DEBUG - Debug CONSOLE
HI 2013-07-22 16:36:13,477 - werkzeug - INFO -  * Running on http://0.0.0.0:5000/

另请注意,使用了带有“ HI”的自定义格式器。

现在查看“ errors.log”文件。它包含了:

2013-07-22 16:36:13,475 - file - DEBUG - Debug FILE
2013-07-22 16:36:13,477 - werkzeug - INFO -  * Running on http://0.0.0.0:5000/
2020-04-06