我正在尝试将Flask中的消息记录到文件和stdout。我一直在阅读官方的Flask文档并想出了这个:
from flask import Flask
import logging
from logging import Formatter, FileHandler
app = Flask(__name__)
@app.route('/')
def hello_world():
app.logger.debug('second test message...')
return 'Hello World!'
if __name__ == '__main__':
#Setup the logger
file_handler = FileHandler('output.log')
handler = logging.StreamHandler()
file_handler.setLevel(logging.DEBUG)
handler.setLevel(logging.DEBUG)
file_handler.setFormatter(Formatter(
'%(asctime)s %(levelname)s: %(message)s '
'[in %(pathname)s:%(lineno)d]'
))
handler.setFormatter(Formatter(
'%(asctime)s %(levelname)s: %(message)s '
'[in %(pathname)s:%(lineno)d]'
))
app.logger.addHandler(handler)
app.logger.addHandler(file_handler)
app.logger.error('first test message...')
app.run()
有几个问题:
output.log
个文件只有第一条日志消息有效:
app.logger.error( '测试...')
只有在stdout中...视图中的那个“/”甚至不打印到stdout ......我做错了什么?
这是启动应用程序并转到/:
的输出2015-03-08 11:33:27,183 ERROR: first test message... [in /home/mosquito/python_projects/flask_tst/flask_tst.py:31]
* Running on http://127.0.0.1:5000/ (Press CTRL+C to quit)
127.0.0.1 - - [08/Mar/2015 11:33:43] "GET / HTTP/1.1" 200 -
答案 0 :(得分:19)
由于您没有在调试模式下运行,Flask会禁止您的(调试)日志消息。如果将以下标志设置为True,则代码将起作用。
app.run(debug=True)
现在,消息将按预期显示。
BennyE$ python3 stackoverflow.py
2015-03-08 12:04:04,650 ERROR: firs test message... [in stackoverflow.py:31]
* Running on http://0.0.0.0:5000/ (Press CTRL+C to quit)
* Restarting with stat
2015-03-08 12:04:04,807 ERROR: firs test message... [in stackoverflow.py:31]
--------------------------------------------------------------------------------
DEBUG in stackoverflow [stackoverflow.py:11]:
second test message...
--------------------------------------------------------------------------------
2015-03-08 12:04:13,789 DEBUG: second test message... [in stackoverflow.py:11]
192.168.178.23 - - [08/Mar/2015 12:04:13] "GET / HTTP/1.1" 200 -
--------------------------------------------------------------------------------
DEBUG in stackoverflow [stackoverflow.py:11]:
second test message...
--------------------------------------------------------------------------------
2015-03-08 12:04:14,899 DEBUG: second test message... [in stackoverflow.py:11]
192.168.178.23 - - [08/Mar/2015 12:04:14] "GET / HTTP/1.1" 200 -
这是相关输出文件中的输出:
BennyE$ cat output.log
2015-03-08 11:58:22,226 ERROR: firs test message... [in stackoverflow.py:31]
2015-03-08 12:04:04,650 ERROR: firs test message... [in stackoverflow.py:31]
2015-03-08 12:04:04,807 ERROR: firs test message... [in stackoverflow.py:31]
2015-03-08 12:04:13,789 DEBUG: second test message... [in stackoverflow.py:11]
2015-03-08 12:04:14,899 DEBUG: second test message... [in stackoverflow.py:11]
答案 1 :(得分:5)
Thansk BennyE_HH,它有效。
但即使调试模式被禁用,Flask也没有抑制ERROR级别日志消息(默认为禁用)。
我认为我们应该调用identify -list configure
来控制日志级别,即使调试模式为false。
答案 2 :(得分:2)
我遇到了同样的问题,以下内容对我有用:
app.logger.setLevel(logging.INFO)