Python 在 Flask 服务器中禁用控制台消息
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14888799/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Disable console messages in Flask server
提问by ATOzTOA
I have a Flask server running in standalone mode (using app.run()). But, I don't want any messages in the console, like
我有一个以独立模式运行的 Flask 服务器(使用app.run())。但是,我不希望控制台中出现任何消息,例如
127.0.0.1 - - [15/Feb/2013 10:52:22] "GET /index.html HTTP/1.1" 200 -
...
How do I disable verbose mode?
如何禁用详细模式?
回答by Drewes
You can set level of the Werkzeug logger to ERROR, in that case only errors are logged:
您可以将 Werkzeug 记录器的级别设置为 ERROR,在这种情况下,只会记录错误:
import logging
log = logging.getLogger('werkzeug')
log.setLevel(logging.ERROR)
Here is a fully working example tested on OSX, Python 2.7.5, Flask 0.10.0:
这是在 OSX、Python 2.7.5、Flask 0.10.0 上测试的完整示例:
from flask import Flask
app = Flask(__name__)
import logging
log = logging.getLogger('werkzeug')
log.setLevel(logging.ERROR)
@app.route("/")
def hello():
return "Hello World!"
if __name__ == "__main__":
app.run()
回答by daicoden
Another reason you may want to change the logging output is for tests, and redirect the server logs to a log file.
您可能想要更改日志输出的另一个原因是为了测试,并将服务器日志重定向到日志文件。
I couldn't get the suggestion above to work either, it looks like loggers are setup as part of the app starting. I was able to get it working by changing the log levels afterstarting the app:
我也无法让上述建议起作用,看起来记录器已设置为应用程序启动的一部分。我能够通过在启动应用程序后更改日志级别来使其工作:
... (in setUpClass)
server = Thread(target=lambda: app.run(host=hostname, port=port, threaded=True))
server.daemon = True
server.start()
wait_for_boot(hostname, port) # curls a health check endpoint
log_names = ['werkzeug']
app_logs = map(lambda logname: logging.getLogger(logname), log_names)
file_handler = logging.FileHandler('log/app.test.log', 'w')
for app_log in app_logs:
for hdlr in app_log.handlers[:]: # remove all old handlers
app_log.removeHandler(hdlr)
app_log.addHandler(file_handler)
Unfortunately the * Running on localhost:9151and the first health check is still printed to standard out, but when running lots of tests it cleans up the output a ton.
不幸的是* Running on localhost:9151,第一个健康检查仍然打印为标准输出,但是在运行大量测试时,它会大量清理输出。
"So why log_names?", you ask. In my case there were some extra logs I needed to get rid of. I was able to find which loggers to add to log_names via:
“那为什么log_names?”,你问。就我而言,我需要删除一些额外的日志。我能够通过以下方式找到要添加到 log_names 的记录器:
from flask import Flask
app = Flask(__name__)
import logging
print(logging.Logger.manager.loggerDict)
Side note: It would be nice if there was a flaskapp.getLogger() or something so this was more robust across versions. Any ideas?
旁注:如果有一个 flaskapp.getLogger() 或其他东西会很好,所以这在不同版本中更加健壮。有任何想法吗?
Some more key words: flask test log remove stdout output
还有一些关键词:flask test log remove stdout output
thanks to:
谢谢:
回答by Tomasz Wojcik
@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.
@Drewes 解决方案大部分时间都有效,但在某些情况下,我仍然倾向于获取 werkzeug 日志。如果你真的不想看到它们中的任何一个,我建议你像那样禁用它。
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.
对我来说,它在abort(500)被提出时失败了。
回答by Ami
In case you are using WSGI server , please set the log to None
如果您使用的是 WSGI 服务器,请将日志设置为无
gevent_server = gevent.pywsgi.WSGIServer(("0.0.0.0", 8080), app,log = None)
回答by iamtodor
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
此解决方案为您提供了一种获取自己的打印和堆栈跟踪的方法,但没有来自烧瓶的信息级别日志,因为 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
回答by Deep state of denial
A brute forceway to do it if you really don't want anything to log into the console beside print() statements is to logging.basicConfig(level=logging.FATAL). This would disable all logs that are of status under fatal. It would not disable printing but yeah, just a thought :/
如果您真的不想在 print() 语句旁边登录控制台,则一种蛮力的方法是将logging.basicConfig(level=logging.FATAL). 这将禁用处于致命状态的所有日志。它不会禁用打印,但是是的,只是一个想法:/
EDIT: I realized it would be selfish of me not to put a link to the documentation I used :) https://docs.python.org/3/howto/logging.html#logging-basic-tutorial
编辑:我意识到不给我使用的文档添加链接是自私的:) https://docs.python.org/3/howto/logging.html#logging-basic-tutorial
回答by Slava V
To suppress Serving Flask app ...:
压制Serving Flask app ...:
os.environ['WERKZEUG_RUN_MAIN'] = 'true'
app.run()
回答by progyammer
Late answer but I found a way to suppress EACH AND EVERY CONSOLE MESSAGE (including the ones displayed during an abort(...)error).
迟到的答案,但我找到了一种方法来抑制每个和每个控制台消息(包括在abort(...)错误期间显示的消息)。
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 Vand Tom Wojcik
这基本上是Slava V和Tom Wojcik给出的答案的组合
回答by Brendan Burkhart
None of the other answers worked correctly for me, but I found a solution based off Peter's comment. Flask apparently no longer uses loggingfor logging, and has switched to the clickpackage. By overriding click.echoand click.sechoI eliminated Flask's startup message from app.run().
其他答案都不适合我,但我找到了基于彼得评论的解决方案。Flask 显然不再logging用于日志记录,并已切换到click包。通过覆盖click.echo,click.secho我从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 ERRORand overriding the click methods with empty functions, all non-error log output should be prevented.
在将日志记录级别设置为ERROR和使用空函数覆盖单击方法之间,应防止所有非错误日志输出。
回答by Anton Erjomin
The first point: In according to official Flask documentation, you shouldn't run Flask application using app.run(). The best solution is using uwsgi, so you can disable default flask logs using command "--disable-logging"
第一点:根据官方 Flask 文档,您不应该使用 app.run() 运行 Flask 应用程序。最好的解决方案是使用 uwsgi,因此您可以使用命令“--disable-logging”禁用默认的烧瓶日志
For example:
例如:
uwsgi --socket 0.0.0.0:8001 --disable-logging --protocol=http -w app:app
uwsgi --socket 0.0.0.0:8001 --disable-logging --protocol=http -w app:app

