Disable console messages in Flask server

前端 未结 10 786
旧巷少年郎
旧巷少年郎 2020-11-28 07:42

I have a Flask server running in standalone mode (using app.run()). But, I don\'t want any messages in the console, like

127.0.0.1 - - [15/Feb/2         


        
相关标签:
10条回答
  • 2020-11-28 08:14

    None of the other answers worked correctly for me, but I found a solution based off Peter's comment. Flask apparently no longer uses logging for logging, and has switched to the click package. By overriding click.echo and click.secho I eliminated Flask's startup message from app.run().

    import logging
    
    import click
    from flask import Flask
    
    app = Flask(__name__)
    
    log = logging.getLogger('werkzeug')
    log.setLevel(logging.ERROR)
    
    def secho(text, file=None, nl=None, err=None, color=None, **styles):
        pass
    
    def echo(text, file=None, nl=None, err=None, color=None, **styles):
        pass
    
    click.echo = echo
    click.secho = secho
    
    @app.route("/")
    def hello():
        return "Hello World!"
    
    if __name__ == "__main__":
        app.run()
    

    Between setting the logging level to ERROR and overriding the click methods with empty functions, all non-error log output should be prevented.

    0 讨论(0)
  • 2020-11-28 08:18

    Late answer but I found a way to suppress EACH AND EVERY CONSOLE MESSAGE (including the ones displayed during an abort(...) error).

    import os
    import logging
    
    logging.getLogger('werkzeug').disabled = True
    os.environ['WERKZEUG_RUN_MAIN'] = 'true'
    

    This is basically a combination of the answers given by Slava V and Tom Wojcik

    0 讨论(0)
  • 2020-11-28 08:22

    In case you are using WSGI server , please set the log to None

    gevent_server = gevent.pywsgi.WSGIServer(("0.0.0.0", 8080), app,log = None)
    
    0 讨论(0)
  • 2020-11-28 08:24

    This solution provides you a way to get your own prints and stack traces but without information level logs from flask suck as 127.0.0.1 - - [15/Feb/2013 10:52:22] "GET /index.html HTTP/1.1" 200

    from flask import Flask
    import logging
    
    app = Flask(__name__)
    log = logging.getLogger('werkzeug')
    log.disabled = True
    
    0 讨论(0)
  • 2020-11-28 08:24

    @Drewes solution works most of the time, but in some cases, I still tend to get werkzeug logs. If you really don't want to see any of them, I suggest you disabling it like that.

    from flask import Flask
    import logging
    
    app = Flask(__name__)
    log = logging.getLogger('werkzeug')
    log.disabled = True
    app.logger.disabled = True
    

    For me it failed when abort(500) was raised.

    0 讨论(0)
  • 2020-11-28 08:30

    To suppress Serving Flask app ...:

    os.environ['WERKZEUG_RUN_MAIN'] = 'true'
    app.run()
    
    0 讨论(0)
提交回复
热议问题