Flask logging - Cannot get it to write to a file

后端 未结 7 1203
野趣味
野趣味 2020-12-04 11:30

Ok, here\'s the code where I setup everything:

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

    applogger = app.logger

    file_handler = FileHandler         


        
相关标签:
7条回答
  • 2020-12-04 12:10

    Why not do it like this:

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

    If you now start you application, you'll see that error.log contains:

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

    For more info, visit http://docs.python.org/2/howto/logging.html

    Okay, as you insist that you cannot have two handler with the method I showed you, I'll add an example that makes this quite clear. First, add this logging code to your main:

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

    Now also add some debug code, so that we see that our setup works:

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

    All what is left is the "logging.conf" program. Let's use that:

    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]
    

    This config is more complicated than needed, but it also shows some features of the logging module.

    Now, when we run our application, we see this output (werkzeug- and 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/
    

    Also note that the custom formatter with the "HI" was used.

    Now look at the "errors.log" file. It contains:

    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/
    
    0 讨论(0)
提交回复
热议问题